我是编程和 C++ 的新手。我很困惑参考在这里的不同之处。
下面的代码输出0 5
但删除&
fromA &GotObj()
将输出0 0
。为什么第二种情况没有输出0 5
?
提前致谢。
#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;
}