第六周项目二:-我的数组类
来源:互联网 发布:一个二次元软件 有后山 编辑:程序博客网 时间:2024/05/17 00:05
【项目2-我的数组类】
下面的程序,因为存在指针类型的数据成员,需要能完成深复制的构造函数。请补充完整构造函数和析构函数(其他不必动)。其中,构造函数要完成下面三个任务:
(1)为各成员函数赋值,按照深复制原则,其中arrayAddr应该是为保存数据新分配的连续空间的首地址;
(2)MyArray(int *a, int n)中,要将a指向的数组中的数值,逐个地复制到新分配的arrayAddr指向的空间中;
(3)getMax( )函数采取的策略是直接返回max(所以,计算max的工作,由构造函数完成)
提示代码:
#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 MyArray::getValue(int i){ //获得数组中下标为i的元素的值 return arrayAddr[i];}int MyArray::getLen(){ //返回数组长度 return len;}int MyArray::getMax( ) { //返回数组中的最大值 return max;}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;}
解决代码:
#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( ); //返回数组中的最大值};MyArray::MyArray(int *a, int n){ int i; len=n; arrayAddr=new int[len]; for(i=0;i<len;i++) { arrayAddr[i]=a[i]; }}MyArray::~MyArray(){ delete []arrayAddr;}int MyArray::getValue(int i){ return arrayAddr[i]; //获得数组中下标为i的元素的值}int MyArray::getLen() //返回数组长度{ return len;}int MyArray::getMax( ) //返回数组中的最大值{ int max=arrayAddr[0]; for(int i=0;i<len;i++) { if(arrayAddr[i]>max) max=arrayAddr[i]; } return max;}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;}
运行结果:
学习心得:构造深复制一个数组类。
0 0
- 第六周项目二:我的数组类
- 第六周——项目二我的数组类
- 第六周 项目二:我的数组类
- 第六周项目二:-我的数组类
- 第六周项目二—我的数组类
- 第六周项目二我的数组类
- 第六周项目二--我的数组类
- 第六周 项目二-我的数组类
- 第六周 项目二--我的数组类
- 第六周项目二——我的数组类
- 第六周项目二我的数组类
- 2015年第六周项目二:我的数组类
- 第六周项目二 我的数组类
- 第六周项目二 我的数组类
- 第六周项目二 我的数组类
- 第六周项目二之我的数组类
- 第六周 项目二 我的数组类
- 第六周 项目二-我的数组类
- FreeMarker学习笔记
- 关于工程科研和工业实践的脱节
- Linux Shell常用技巧(三) sed
- spring mvc3.2启动分析
- JAVA中正则表达式总结
- 第六周项目二:-我的数组类
- [Note]LibreOffice和Calligra组件
- 【双Treap】[Scoi2014] bzoj3595 方伯伯的Oj
- IntelliJ IDEA 14.0.3取消警告
- Linux中profile、bashrc、bash_profile之间的区别和联系
- 火狐被墙了!
- Android 代码混淆 选项说明
- Linux chkconfig命令实例-【linux学习笔记】
- linux HAXM