您的位置:首页 > 其它

第9周项目二-我的数组类

2016-05-06 21:06 387 查看
代码:

/*
*Copyright (c) 2016, 烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:main.cpp;
*作    者:岳成艳;
*完成日期:2015年5月6号;
*版 本 号:vc++6.0;
*
*问题描述:(1)为各成员函数赋值,其中arrayAddr应该是为保存数据新分配的连续空间的首地址;注意需要深复制的构造函数
(2)将a指向的数组中的数值,逐个地复制到新分配的空间中 。
*程序输入:无;
*程序输出:见运行测试;
*/
#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)
{
arrayAddr = new int
;
arrayAddr = a;
len = n ;
}

MyArray::~MyArray()
{
delete []arrayAddr;
}
int MyArray::getValue(int i)  //获得a指向的数组下标为i的元素值
{
return arrayAddr[i];
}

int MyArray::getLen()   //返回数组长度
{
return len;
}

int MyArray::getMax()         //返回数组中的最大值
{
max=arrayAddr[0];
for(int i = 0 ; i < len ; i++ )
{
if(max < arrayAddr[i])
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;
}
运行测试:



知识点总结:

深复制:当被复制的对象数据成员是指针类型时,要为其专门分配空间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: