條款 10:令 operator= 返回一個 reference to *this

條款 10:令 operator= 返回一個 reference to *this

Have assignment operators return a reference to *this.

爲了下列實現“連鎖賦值”,需要令賦值操作符返回一個操作符左側實參的引用

a = b = c = 15;
Widget& operator=(const Widget& ths)
{
    ...
    return *this;
}

Widget& operator=(int rhs)
{
    ...
    return *this;
}

這並非強制性,但所有內置類型和標準程序庫提供的類型如:string、vector、complex、shared_ptr 都遵守。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章