class B
{
};
class A
{
public:
A& operator=(const A& a)
{
B* temp = b; //先用一个临时指针指向自己
b = new B(*a.b);//关键复制,就是把b=new B;b=a.b;分开写
delete temp; //删掉过去的自己,delete 尽量后面写,万一delete后有抛出异常这些什么就很尴尬
return *this;
}
B* b;
};
int main()
{
int a = 3;
int *b = &a;
int *c = new int(*b);//新的new 方法,两条语句合在一起写
int *d = new int;//和上面的同一个意思
d = b;
int *e = new int(a);//和上面的一个意思
cout << *b << endl << *c << endl << *d << endl << *e;
}
还有一种copy and swap的方法
A& operator=(const A& rhs)
{
A temp(rhs);
swap(temp);//iostream标准库即可,但不行不知道书原因还是?
// swap(temp, *this);出错
return *this;
}
A& operator=( A rhs)
{
swap(rhs);
return *this;
}
原文:http://www.cnblogs.com/vhyc/p/5581555.html