【项目1-深复制体验】参考解答 (1)阅读下面的程序,补足未完成的注释
#include<iostream> #include<cstring> using namespace std; class A { private: char *a; public: A(char *aa) { a = new char[strlen(aa)+1]; //(a)这样处理的意义在于:______________________________ strcpy(a, aa); //(b)数据成员a与形式参数aa的关系:___________________________________ } ~A() { delete []a; //(c)这样处理的意义在于: ___________________________________________ } void output() { cout<<a<<endl; } }; int main(){ A a("good morning, code monkeys!"); a.output(); A b("good afternoon, codes!"); b.output(); return 0; }(2)将注释(a)所在的那一行去掉,会出现什么现象?为什么?为什么a数据成员所占用的存储空间要在aa长度基础上加1?若指针a不是指向字符(即不作为字符串的地址),是否有必要加1? (3)为类A增加复制构造函数,用下面的main函数测试
int main() { A a("good morning, code monkeys!"); a.output(); A b(a); b.output(); return 0; }【项目2-我的数组类】参考解答 阅读程序,请完成成员函数的定义,因为存在指针型的数据成员,注意需要深复制的构造函数。
#include<iostream> using namespace std; class MyArray { private: int *arrayAddr; //保存一个有len个整型元素的数组的首地址 int len; //记录动态数组的长度 int max; //动态数组中的最大值(并非动态数组中必须要的数据成员) public: MyArray(int *a, int n); ~MyArray(); int getValue(int i); //获得数组中下标为i的元素的值 int getLen(); //返回数组长度 int getMax( ); //返回数组中的最大值 }; //写出各成员函数的定义 int main() { int b[10]= {75, 99, 90, 93, 38, 15, 5, 7, 52, 4}; MyArray r1(b,10); cout<<"最大值:"<<r1.getMax()<<endl; int c[15] = {18,68,10,52,3,19,12,100,56,96,95,97,1,4,93}; MyArray r2(c,15); int i,s=0; for(i=0; i<r2.getLen(); i++) s+=r2.getValue(i); cout<<"所有元素的和为:"<<s<<endl; return 0; }【项目3-人数不定的工资类】参考解答 设计一个工资类(Salary),其中的数据成员包括职工人数(number,人数不定)和number个职工的工资salary,要求输入职工工资并逐个输出。
提示:用固定大小的数组存储number个职工的工资,可能造成空间的浪费,也可能会由于空间不够而不能处理职工人数过多的应用。将salary声明为指针类型的成员,通过动态分配空间,分配正好大小的空间存储数据。
class Salary { public: Salary(int n); //n为职工人数,初始化时完成空间的分配 ~Salary(); //析构函数中释放初始化时分配的空间 void input_salary(); void show_salary(); private: double *salary; int number; }; //下面定义类的成员函数 …… //下面是测试函数 int main() { Salary s(10); s.input_salary(); s.show_salary(); return 0; }