万能胶水:c++构造函数问题

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/30 05:37:06
构造有个动态组类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];
for(int i=0;i<a.length;++i) ins>>a[i];
return ins;
}

ostream& operator << (ostream& outs,CArray & a)
{
for(int i=0;i<a.length;++i) outs<<a[i]<<' ';
outs<<endl;
return outs;
}

int main()
{
CArray a;
cin>>a;
CArray b(a);
cout<<b.size()<<endl;
if(a==b)cout<<b;
cin>>b[0];
if(!(a==b))cout<<b;
/*
重载>>:先输入元素个数,再依次输入各个元素
重载<<:依次输出各个元素的数值
输入样例:
3
1 2 3
4
输出:
3
1 2 3
4 2 3
*/
//system("pause");
return 0;
}

class carray{
public:
carray()
{ptr=NULL;
length=0;
}
carray(const char& c)
{
while(*c!='\0') {length++;c++;}
ptr=new char[length+1];
}
int len(const char& c)
{
while(*c!='\0') {length++;c++;}
return length;}
~carray()
{
delete[] ptr;}

参考MFC的CArray类就可以...

或者直接拿来用!呵呵