标签:
对于非内部类对象的赋值,会存在一个默认的赋值运算符重载函数。
如下面的代码中,c2=c1这句中调用了类A的默认的赋值运算符重载函数,实现了c2.real=c1.real; c2.image=c1.image;
class A{ private: int real; int image; public: A(int r,int i) { real=r; image=i; } }; int main() { A c1(1,2); A c2(0,0); c2=c1; }
class A{ private: char *name; char *namep; public: A(A& a1) { if(a1.name) { name=new char[strlen(a1.name)+1]; strcpy(name,a1.name); } if(a1.namep) { namep=new char[strlen(a1.namep)+1]; strcpy(namep,a1.namep); } } A &operator =(A &a1) { if(name) delete []name; if(namep) delete []namep; if(a1.name) { name=new char[strlen(a1.name)+1]; strcpy(name,a1.name); } else name=NULL; if(a1.namep) { namep=new char[strlen(a1.namep)+1]; strcpy(namep,a1.namep); } else namep=NULL; return *this; } };
标签:
原文地址:http://www.cnblogs.com/beaglebone/p/5727161.html