条款10:令operator=返回一个reference to *this

关于赋值,我们知道可以连续的进行赋值如:

         int x, y, z; x = y = z = 12;

为了实现连锁的赋值,赋值操作符必须返回一个reference指向操作符的左侧实参,这是你要为class实现赋值操作符时,应该遵循的协议:

class Widget {

public :

         ...

         Widget& operator= (const Widget& rhs){

                   ...

                   return *this;

         }

}

 

这个协议不仅适用于以上的标准赋值形式,也适用于所有的赋值相关运算,例如:

class Widget {

public :

         ...

         Widget& operator= (const Widget& rhs){

                   ...

                   return *this;

         }

         Widget& operator+= (const Widget& rhs){

                   ...

                   return *this;

         }

}

 

 

请记住:

  • 令赋值操作符返回一个reference to *this
posted @ 2012-11-15 22:30  loveyakamoz  阅读(240)  评论(0编辑  收藏  举报