c++构造函数问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 19:32:16
构造有个动态组类CArray,该类有以下几个私有数据成员:
int *ptr;//指向数组的首地址
int length;
要求至少实现以下操作:
1.缺省构造函数
2.拷贝构造函数
3.求数组长度
4.析构函数
5.重载运算符:==,[],>>,<<

老师布置的作业~~好难啊~~~那位高手帮我下~~谢谢了~~要完整的~~~
满足条件可以运行就行了~~~
我追加分给你们~~~决不失言~~~~

//修改了一下
#include <iostream>
using namespace std;

class CArray
{
int *ptr;
int length;
public:
CArray():ptr(NULL),length(0){}
CArray(const CArray & a)
{
ptr=new int[length=a.length];
for(int i=0;i<length;++i) ptr[i]=a.ptr[i];
}
int size(){return length;}
~CArray(){if(length!=0) delete [] ptr;}
bool operator ==(const CArray a) const
{
if(length!=a.length) return 0;
for(int i=0;i<length;++i)if(ptr[i]!=a.ptr[i]) return 0;
return 1;
}
int & operator [](int i){return ptr[i];}
friend istream& operator >> (istream& ins,CArray & a);
friend ostream& operator << (ostream& outs,CArray & a);
};

istream& operator >> (istream& ins,CArray & a)
{
if(a.length!=0) delete [] a.ptr;
ins>>a.length;
a.ptr=new int[a.length];