*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************
Ii. Constructors,destructors and Assignment Operators
Rule 10:have Assignment operators return a reference to *this
Rule 10: Make operator= return a reference to *this
With regard to assignment, there is a very interesting chain code:
int x,y,z;x = y = z = n; Chained form of assignment
Moreover,C + + adopts right associative law, if you use parentheses to represent the order of precedence, this is the case:
x = (y = (z = 15));
in C + +, in order to implement "chained assignment", the assignment operator must return a reference to the left argument of the operator. (Note that this is the protocol that classes should follow when implementing the assignment operator )
<span style= "FONT-SIZE:14PX;" >class Widget {public: ... widget& operator= (const widget& RHS) <span style= "WHITE-SPACE:PRE;" ></span>//return type is a reference { ... return* this;<span style= "WHITE-SPACE:PRE;" ></span>//return to left object } ...}; </span>
and this Protocol applies not only to the above standard assignment form, but also to all assignment-related operations , such as + =,-=, *=, etc.:
widget& operator+= (const widget& RHS) { ... return *this;}
However,Note that this is only an agreement and is not mandatory, and if you do not follow it, the code can be compiled. However, this agreement is adhered to by all built-in types and standard library types, such as String, vector, complex,trl::shared_ptr, etc.
So unless there's enough reason to be different, it's a herd.
☆ Please remember
Enables the assignment (Assignment) operator to return a reference to *this.
*************************************** Reprint Please specify the Source: Http://blog.csdn.net/lttree ********************************************
"Effective C + +" study notes-clause 10