Why Operator = Operator returns a reference

zhaozj2021-02-08  280

VCKBASE ONLINE HELP JOURNAL NO.10

Why is Operator = Operator Returns Zhao Xiangning Problem: The MSDN documentation is explained in: operator = Operator defaults to return reference --Type & Type :: Operator = (const type &) Why? I understand this is: "=" is a binary operator. Its incoming parameters are reference objects, while other parameters are class instances, "=" is overloaded in this class instance. I can implement assignment operators without returning any type (Void) in practical applications, and can still be completed. Do you do it correctly? If not correct, why is the default implementation return reference? Answer: If you take some time to think about it, you will have an answer. it's actually really easy. Operator = Reasons for returning references are to enable you to connect multiple assignments in one statement. Type A, B, C, D; ... a = b = c = D; the compiler is like this to explain the front line: a = (b = (c = d)); during the compilation process, the assignment is the right binding . To put it bluntly, if you want to play multiple assignments, Operator = returned must be the right (RHS) assignment. What else can I have to return to the object itself? That's why Operator = The last line always returns reference to this: CMYCLASS & CMYCLASS :: Operator = (const cmyclass & rhs) {... // do the // AssignmentReturn * this;}; RHS parameter is declared The constant is allowed to assign the common object. There is no reason not to allow. Why is Operator = Returns a very quite reference? So, no matter where you can use the assignment statement to reference: void myfunc (type & a); ... type a, b; myfunc (a = b); // Passing after the value of Operator = Return very quantity, you It can even use a circular arc overload typical alignment: Type A, B, C; (a = b) = C; Figure 1 is a simple example. And there is a question: What is its output when you finish and run foo? If you want to learn more about assignment, I strongly recommend a book "Effective C " author is Scott Meyers. This book is published by Addison Wesley Longman, 1997.

© 1997-2000 vckbase.com All rights reserved.

转载请注明原文地址:https://www.9cbs.com/read-1623.html

New Post(0)