第6周项目我的数组类
来源:互联网 发布:海康网络摄像机ip地址 编辑:程序博客网 时间:2024/06/13 01:22
#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( ); //返回数组中的最大值
};
//为各成员函数赋值,按照深复制原则,其中arrarAddr应该是为保存数据新分配的连续空间的首地址
//MyArray(int*a,int n)中,要将a指向的数组中的数值,逐个的复制到新分配的arrayAddr指向的空间中
//getMax()函数采取的策略是直接返回max(所以,计算 max的工作,由构造函数完成
MyArray::MyArray(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(a[i]>max)
max=a[i];
}
}
MyArray::~MyArray()
{
delete []arrayAddr;
}
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( ); //返回数组中的最大值};//为各成员函数赋值,按照深复制原则,其中arrarAddr应该是为保存数据新分配的连续空间的首地址//MyArray(int*a,int n)中,要将a指向的数组中的数值,逐个的复制到新分配的arrayAddr指向的空间中//getMax()函数采取的策略是直接返回max(所以,计算 max的工作,由构造函数完成MyArray::MyArray(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(a[i]>max) max=a[i]; }}MyArray::~MyArray(){ delete []arrayAddr;}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;}
学习总结:
数组深复制: arrayAddr=new int[n];
析构函数: delete []arrayAddr的格式
- 第6周项目2我的数组类
- 第6周项目我的数组类
- 第6周项目2-我的数组类
- 第6周项目-我的数组类
- 第6周项目2-我的数组类
- 第6周项目2-我的数组类
- 第6周项目1-我的数组类
- 2015-第6周项目2-我的数组类
- 第6周项目2我的数组类
- 第5周项目2-我的数组类
- 第9周-项目2-我的数组类
- 第9周项目2:我的数组类
- 第9周项目2 我的数组类
- 第9周项目2-我的数组类
- 第9周项目二-我的数组类
- 第9周项目2—我的数组类
- 第9周项目2-我的数组类
- 第9周项目2- 我的数组类
- PHP的pcntl多进程
- Android Fragment 真正的完全解析(上)
- 谈谈对HandlerThread的理解
- 2015第六届蓝桥杯全国软件大赛省赛(预赛)总结
- Android NDK 开发环境搭建(二)----来源http://www.cnblogs.com/zdz8207/archive/2012/11/27/android-ndk-install.htm
- 第6周项目我的数组类
- Python对数组的基本操作
- 二分查找
- ios真机调试之二真机测试
- 搜索引擎-倒排索引基础知识
- openwrt 的串口与网络通信
- Cocos 2.2.1 + cocos2d-x 3.5 集成protobuf
- AIX巡检脚本
- 连接查询