[英]Operator overloading returning a reference
I am trying to understand what is the real deal with returning a reference, while studying operator overloading.在研究运算符重载时,我试图了解返回引用的真正含义是什么。 I create this very simple problem:
我创建了这个非常简单的问题:
#include <iostream>
using namespace std;
class mydoub {
public:
double pub;
mydoub(double i = 0) : pub(i) {}
};
mydoub &operator += (mydoub &a, double b) {
a.pub = a.pub+b;
return a;
}
int main() {
mydoub a(5), b(6);
cout << "1: " << a.pub << " " << b.pub << endl; // expected output 1: 5 6
b = a+= 7;
cout << "2: " << a.pub << " " << b.pub << endl; // expected output 2: 12 12
b.pub = 8;
cout << "3: " << a.pub << " " << b.pub << endl; // unexpected output: 3: 12 8
}
The output is:输出是:
1: 5 6
2: 12 12
3: 12 8
which is quite unexpected to me.这对我来说很出乎意料。 In fact,
b
has been assigned a reference to a
, right after the latter has been modified, so I expect b.pub=8
to act on a
as well, as a result of the reference passing through the operator +=
.事实上,
b
已被分配给一个参考a
,后者已被修改后的权利,所以我希望b.pub=8
作用于a
为好,为穿过操作者参考的结果+=
。 Why isn't it so?为什么不是这样? What is then the difference with a non-reference overload, say
mydoub operator += ( ..
?那么与非引用重载有什么区别,比如说
mydoub operator += ( ..
?
You are messing with an understanding of reference.你搞乱了对参考的理解。 Reference, in fact, is just dereferenced pointer and when you do
b = a
, it is actually copying the a value to b, they are not pointing to the same object.实际上,引用只是取消引用的指针,当您执行
b = a
,它实际上是将 a 值复制到 b,它们并不指向同一个对象。 To point to the same object you need to use pointers or make b not mydoub type, but mydoub& type (in that case, while initializing you can point to the same object).要指向同一个对象,您需要使用指针或使 b 不是 mydoub 类型,而是 mydoub& 类型(在这种情况下,在初始化时您可以指向同一个对象)。
mydoub& operator += is used to can modify the result of += operator. mydoub& 运算符 += 用于修改 += 运算符的结果。 For example,
例如,
mydoub a = 1;
++(a += 3)
After that a will 5, but if you use mydoub operator += it will be 4.之后是 5,但如果你使用 mydoub 运算符 += 它将是 4。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.