什么时候用拷贝构造函数,和赋值构造函数: 浅拷贝和深拷贝 下面是例子,注意看两种函数怎么写,什么地方用到: #include <iostream> using namespace std; class CA { public: CA(int b,char* cstr) { a=b; str=new char[b]; strcpy(str,cstr); } CA(const CA& Other) //拷贝构造函数 { a=Other.a; str=new char[a]; //深拷贝 if(str!=0) strcpy(str,Other.str); } CA & operator = (const CA& Other) //赋值符重载 { a=Other.a; //复制常规成员 // (1) 检查自赋值 if(this == &Other) return *this; // (2) 释放原有的内存资源 delete [] str; // (3) 分配新的内存资源,并复制内容 str = new char[a]; strcpy(str,Other.str); // (4) 返回本对象的引用 return *this; } void Show() { cout<<str<<endl; } ~CA() { delete str; } private: int a; char *str; }; int main() { CA A(10,"Hello!"); CA B=A; B.Show(); CA C(9,"world!"); C = B; return 0; } 下面是另外一个例子,修改了下里面的赋值构造函数,把temp变量去掉了,这样更省空间吧? class CExample { ... CExample(const CExample&); //拷贝构造函数 CExample& operator = (const CExample&); //赋值符重载 ... }; //拷贝构造函数使用赋值运算符重载的代码。 CExample::CExample(const CExample& RightSides) { pBuffer=NULL; *this=RightSides //调用重载后的"=" } //赋值操作符重载 CExample & CExample::operator = (const CExample& RightSides) { nSize=RightSides.nSize; //复制常规成员 char *temp=new char[nSize]; //复制指针指向的内容 memcpy(temp,RightSides.pBuffer,nSize*sizeof(char)); delete []pBuffer; //删除原指针指向内容 (将删除操作放在后面,避免X=X特殊情况下,内容的丢失) pBuffer=temp; //建立新指向 return *this } //其实也没啥改进,但觉得这样的写法是不是更好?省了一个temp临时变量。 CExample & CExample::operator = (const CExample& RightSides) { nSize=RightSides.nSize; //复制常规成员 delete []pBuffer; //删除原指针指向内容 (将删除操作放在后面,避免X=X特殊情况下,内容的丢失) pBuffer=new char[nSize]; //建立新指向 memcpy(pBuffer,RightSides.pBuffer,nSize*sizeof(char)); return *this } |
|