Problem:
explained in the MSDN documentation: the operator= operator returns a reference by default--
type& type::operator= (const type&)
Why, then? My understanding of this is that "=" is a binary operator. The arguments passed in are reference objects, while the other arguments are class instances, and "=" is overloaded in this class instance. In practice, I can not return any type (void) to implement the assignment operator, and still be able to complete the assignment operation. Am I doing the right thing? If not, then why does the default implementation return the reference?
Answer:
If you spend a little more time thinking about it, you may have an answer. It's actually very simple. The reason operator= returns a reference is that you can connect multiple assignments in a single statement.
TYPE a,b,c,d;
...
A = b = c = D;
The compiler interprets the previous line like this:
A = (b = (c = d));
In the compilation process, the assignment is the right combination. The thing is, if you want to play with multiple assignments, the operator= return must be assigned a right (RHS) value. What can you do other than return a reference to the object itself? That's why the last line of operator= always returns a reference to this:
cmyclass& cmyclass::operator= (const cmyclass& RHS) {
......
Do the
Assignment
return *this;
};
RHS parameter is declared as constant, the assignment of a constant object is allowed. There is no reason not to allow. Why operator= to return a very important reference? So no matter where you are, you can use an assignment statement to reference the type:
void MyFunc (type& a);
...
TYPE a,b;
MyFunc (A=B); Assign values to pass after
Because operator= returns a very heavy amount, you can even use parentheses to overload the usual equal-rate combination:
TYPE A,b,c;
(A = b) = C;
Figure I is a simple example. And there's a question: What's the output when you finish and run Foo?
If you want to learn more about assignment operations, I strongly recommend a book, "Effective C + +," the author of Scott Meyers. The book is published by Addison Wesley Longman, 1997.