令operator=返回一個引用指向*this

字號:

一般的連鎖賦值方式:
    int x, y, z;
    x = y = z = 15;//等價于x = (y = (z = 15));
    當(dāng)我們要實現(xiàn)自己的operator=操作時,就需要返回一個引用,加入收藏該引用指向了操作符左側(cè)的參數(shù);
    1 class Widget
    2 {
    3 public:
    4  
    5   Widget& operator=(const Widget& rhs)
    6   {
    7    
    8     return *this;//返回*this
    9   }
    10 };
    這個*this是所以c++標(biāo)準(zhǔn)實現(xiàn)中的規(guī)范做法,不這樣做也可以通過編譯,不過既然是規(guī)范,就遵守一下吧!