[英]What is the importance of returning reference in operator overloading
任何人都可以解释为什么在重载运算符时需要返回引用,例如
friend std::ostream& operator<< (std::ostream& out, const std::string& str)
It is to make "chaining" of the operator work, in examples like this: 在这样的例子中,它是对操作员的“链接”工作:
std::cout << "hello," << " world";
If the first (leftmost) use of the operator<<()
hadn't returned a reference, there would not be an object to call for the second use of the operator. 如果
operator<<()
的第一个(最左边)使用没有返回引用,则不会有一个对象要求第二次使用该运算符。
这是为了操作符链接(如果你返回一个指针,你必须取消引用它),并且不要制作一个可能庞大且昂贵的对象副本(如果你返回一个值),如果它甚至可以这样做的话。
A general rule, stated by Scott Meyers in Effective C++, is that when in doubt, "do as the ints
do". 一般情况下,斯科特迈尔斯在有效的C ++说,是有疑问时,“做的
ints
做”。 So for example, operator= should return a reference so code like this works: 因此,例如,operator =应该返回一个引用,所以这样的代码有效:
MyClass A, B, C;
A = B = C = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.