求教,赋值符重载,怎样写更好?有没有什么建议和要遵守的规则?
不才试了下赋值构造函数,也就是赋值符重载,依葫芦画瓢给加了个赋值符重载,请各位能否看看对不对,有没有更好的写法
#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;} 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}