课程首页在:http://blog.csdn.net/sxhelijian/article/details/11890759,内有完整教学方案及资源链接
【项目2-再一个深复制】
下面的程序,因为存在指针类型的数据成员,需要能完成深复制的构造函数。请补充完整构造函数和析构函数(其他不必动)。其中,构造函数要完成下面三个任务:
(1)为各成员函数赋值,其中arrayAddr应该是为保存数据新分配的连续空间的首地址;
(2)将a指向的数组中的数值,逐个地复制到新分配的空间中
(3)getMax( )函数采取的策略是直接返回max,计算max的工作,由构造函数完成
#include<iostream> using namespace std; class A { private: int *arrayAddr;//保存一个有len个整型元素的数组的首地址 int len; //记录动态数组的长度 int max; //动态数组中的最大值(并非动态数组中必须要的数据成员) public: A(int *a, int n); ~A(); int getValue(int i); //获得a指向的数组中下标为i的元素的值 int getLen(); //返回数组长度 int getMax( ); //返回数组中的最大值 }; int A::getValue(int i){ //获得a指向的数组中下标为i的元素的值 return arrayAddr[i]; } int A::getLen(){ //返回数组长度 return len; } int A::getMax( ) { //返回数组中的最大值 return max; } int main(){ int b[10]= {75, 99, 90, 93, 38, 15, 5, 7, 52, 4}; A 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}; A r2(c,15); int i,s=0; for(i=0; i<r2.getLen(); i++) s+=r2.getValue(i); cout<<"所有元素的和为:"<<s<<endl; return 0; }
参考解答:
#include<iostream> using namespace std; class A { private: int *arrayAddr;//保存一个有len个整型元素的数组的首地址 int len; //记录动态数组的长度 int max; //动态数组中的最大值(并非动态数组中必须要的数据成员) public: A(int *a, int n); ~A(); int getValue(int i); //获得a指向的数组中下标为i的元素的值 int getLen(); //返回数组长度 int getMax( ); //返回数组中的最大值 }; //定义构造函数,构造函数要完成下面三个任务: //(1)为各成员函数赋值,其中arrayAddr应该是为保存数据新分配的连续空间的首地址; //(2)将a指向的数组中的数值,逐个地复制到新分配的空间中 //(3)getMax( )函数采取的策略是直接返回max,计算max的工作,由构造函数完成 A::A(int *a, int n) { len=n; arrayAddr=new int[n]; max=a[0]; for(int i=0; i<n; i++) { arrayAddr[i]=a[i]; if (max<a[i]) max=a[i]; } } //析构函数的类外定义,释放指针型数据a所指向的空间 A::~A() { delete [] arrayAddr; } int A::getValue(int i) //获得a指向的数组中下标为i的元素的值 { return arrayAddr[i]; } int A::getLen() //返回数组长度 { return len; } int A::getMax( ) //返回数组中的最大值 { return max; } int main() { int b[10]= {75, 99, 90, 93, 38, 15, 5, 7, 52, 4}; A 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}; A r2(c,15); int i,s=0; for(i=0; i<r2.getLen(); i++) s+=r2.getValue(i); cout<<"所有元素的和为:"<<s<<endl; return 0; }
==================== 迂者 贺利坚 CSDN博客专栏================= |== IT学子成长指导专栏 专栏文章的分类目录(不定期更新) ==| |== C++ 课堂在线专栏 贺利坚课程教学链接(分课程年级) ==| |== 我写的书——《逆袭大学——传给IT学子的正能量》 ==| ===== 为IT菜鸟起飞铺跑道,和学生一起享受快乐和激情的大学 ===== |