一、重载operator=返回类型
下面举例说明,operator=类似。
针对:ostream & operator <<(ostream & os, const ClassType &object)
二、解决operator=自我赋值问题
在实现operator=时考虑自我赋值是必要的就像 x=y ,我们不知道变量x与y代表的值是否为同一个值(把x和y说成是一个指针更恰当一点)。如下
class bitmap{};
class Widget{
public:
Widget& operator=(const Widget& rhn);
private:
bitmap *pb; //定义一个指针指向对分配的空间
}第一版赋值函数:Widget& Widget::operator=(const Widget& rhs)
{
delete pb;
pb = new bitmap(*rhs.pb);
return this;
}这般函数的pb在使用前清理掉之前的pb指向,在接受一个new出来的新对象,看着很顺理成章,但当 this 与函数的参数rhs相等时pb = new bitmap(*rhs.pb);会执行出错,因为我们已经把*rhs.pb delete了。Widget& Widget::operator=(const Widget& rhs)
{
if(*this == rhs)
return *this;
delete pb;
pb = new bitmap(*rhs.pb)
return *this;
}这个版本的赋值函数基本上是可以接受的,但不见的是安全的,因为当new产生异常时pb依然是个不确定的指针。Widget& Widget::operator=(const Widget& rhn)
{
bitmap *pOrig = pb;
pb = new bitmap(*rhn.pb);
delete pOrig;
return this;
} 这个函数在开始时用pOrig记录了pb,当new没有异常时我们在把Pb原来的指向空间释放掉,从而提高了安全性。class Widget {
void swap(const Widget& rhs);
}
Widget& Widget::operator=(const Widget& rhs)
{
Widget temp(rhs); //防止改变rhs
swap(temp);
return *this;
}当然我们也可以by value 传递参数Widget& Widget::operator=(const Widget rhs) //按值传递是实参的一个copy
{
swap(temp);
return *this;
}copy and swap技术的缺点是巧妙的运用swap丧失了代码的清晰性,然而将“copy动作”移动到函数参数的构造阶段令编译器有时生成高效的代码..
三、operator=重载函数、copy构造函数和构造函数深层复制
很容易理解啦,就是在子类中实现上述函数时,不要忘了调用基类的相应函数来复制、赋值和初始化继承而来的那部分变量!!
effective c++条款10-12(operator=(重载返回类型、自我赋值和深层复制))整理
原文:http://blog.csdn.net/hustyangju/article/details/41624083