Clause 10: Operator= returns a reference to *this;
On assignment, we can write:
int x,y,x;
x =y = Z;
This is called continuous assignment.
In order to implement the "chained assignment" assignment operator, you must return a reference to the left argument of the operator. This is the protocol that we should follow when we implement the assignment operator for class:
#include <iostream>using namespace Std;class widget{public:widget () {cout<< "call no parameter Constructor" <<ENDL;} Widget (const widget& W) {cout<< "Call copy constructor" <<endl;} ~widget () {}widget& operator= (const widget& RHS)//return type is a reference point to the current object {cout<< "Hello" <<endl; Return *this;//returns the left object}widget& operator + = (const widget& RHS)//This protocol also applies to +=,-=,*= and so on {return *this;}}; int main () {Widget W1; Widget W2; Widget w3;w1 = W2 = W3;return 0;}
It says that the assignment operator must return a reference, and I used to think that if I was going to continue, I would have to return a reference, but I tried to run it back with an object,
The program also passes, and in this operator= you get the exact same effect:
It is found that it is not necessary to return a reference, the return value object will increase the copy constructor and the call of the destructor, so it is generally a return reference;
#include <iostream>using namespace Std;class widget{public:widget () {cout<< "call no parameter Constructor" <<ENDL;} Widget (const widget& W) {cout<< "Call copy constructor" <<endl;} ~widget () {}/*widget& operator= (const widget& RHS)//return type is a reference point to the current object {cout<< "Hello" <<endl; Return *this;//returns the left object}*/widget operator= (const widget& RHS) {cout<< "Hello" <<endl;return *this;}; int main () {Widget W1; Widget W2; Widget w3;w1 = W2 = W3;return 0;} /*1: Call return Reference: Call parameterless constructor call parameterless constructor call parameterless constructor HelloHello2: Call return object call parameterless constructor call parameterless constructor call no parameter constructor Hello call copy constructor Hello call copy constructor press Any key to continue*/
Effective C + + reading notes clause 10