[英]C++ class member function with reference return type
I am a newbie to programming and C++. 我是编程和C ++的新手。 I'm confused how reference works differently here.
我很困惑这里引用如何工作。
The code below outputs 0 5
but removing the &
from A &GotObj()
would output 0 0
. 下面的代码输出
0 5
但是从A &GotObj()
删除&
将输出0 0
。 Why didn't the second case output 0 5
? 为什么第二种情况不输出
0 5
?
Thanks in advance. 提前致谢。
#include <iostream>
using namespace std;
class A {
public:
int val;
A(int n=0) {
val = n;
}
A &GetObj() {
return *this;
}
};
int main() {
A a;
cout << a.val << endl;
a.GetObj() = 5;
cout << a.val << endl;
return 0;
}
When you return by value the expression a.GetObj()
just creates a temporary. 当按值返回时,表达式
a.GetObj()
只会创建一个临时值。 Assigning then only changes the value of that temporary. 然后分配仅更改该临时值。
This of a reference as just a pointer with a slightly different syntax. 这个引用只是一个语法稍有不同的指针。 When
GetObj
is defined as 当
GetObj
定义为
A& GetObj() { return *this: }
it returns a reference (ie a pointer) to a. 它返回对a的引用(即指针)。 Then, the assignment
然后,分配
a.GetObj() = 5
effectively invokes the assignment operator of a
with the argument 5, which changes the value of a to 5. 有效地调用的赋值运算符
a
用参数5,其改变的一个至5的值。
But if you define GetObj()
as 但是,如果您将
GetObj()
定义为
A GetObj { return *this; }
it returns a completely new temporary object that has the same value as a. 它返回一个与a值相同的全新临时对象。 So when you later assign 5 to it, it doesn't change the value of a.
因此,当您以后为其分配5时,它不会更改a的值。
Case 1: A GetObj()
情况1:一个GetObj()
A a;
A a;
a.GetObj() = 5
a.GetObj()= 5
Case 2: A &GetObj()
情况2:A&GetObj()
A a;
A a;
a.GetObj() = 5
a.GetObj()= 5
will reflect effect in object a. 将反映对象a的效果。 and now printing value of variable val will be as expected 5.
现在变量val的打印值将达到预期的5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.