關于 assignments(指派)的一件有意思的事情是你可以把它們穿成一串。
int x, y, z;
x = y = z = 15; // chain of assignments
另一件有意思的事情是 assignment(指派)是 right-associative(右結合)的,是以,上面的指派串可以解析成這樣:
x = (y = (z = 15));
這裡,15 賦給 z,然後将這個 assignment(指派)的結果(最新的 z)賦給 y,然後将這個 assignment(指派)的結果(最新的 y)賦給 x。
這裡的實作方法是讓 assignment(指派)傳回一個 reference to its left-hand argument(引向它的左側參數的引用),而且這就是當你為你的 classes(類)實作 assignment operators(指派運算符)時應該遵守的慣例:
class Widget {
public:
...
Widget& operator=(const Widget& rhs) // return type is a reference to
{ // the current class
...
return *this; // return the left-hand object
}
...
};
這個慣例适用于所有的 assignment operators(指派運算符),而不僅僅是上面那樣的标準形式。是以:
class Widget {
public:
...
Widget& operator+=(const Widget& rhs // the convention applies to
{ // +=, -=, *=, etc.
...
return *this;
}
Widget& operator=(int rhs) // it applies even if the
{ // operator's parameter type
... // is unconventional
return *this;
}
...
};
這僅僅是一個慣例,代碼并不會按照這個意願編譯。然而,這個慣例被所有的 built-in types(内建類型)和标準庫中(或者即将進入标準庫——參見 Item 54)的 types(類型)(例如,string,vector,complex,tr1::shared_ptr 等)所遵守。除非你有好的做不同僚情理由,否則,不要破壞它。
Things to Remember
- 讓 assignment operators(指派運算符)傳回一個 reference to *this(引向 *this 的引用)。