【发布时间】:2022-01-03 16:28:20
【问题描述】:
我在第二次 getter 调用中获得了意想不到的价值,这对我来说看起来不对,发生这种情况有什么具体原因吗?
#include<iostream>
using namespace std;
class Test {
public:
int &t;
Test (int x):t(x) { }
int getT() { return t; }
};
int main() {
int x = 20;
Test t1(x);
cout << t1.getT() << " ";
cout << t1.getT() << endl;
return 0;
}
【问题讨论】:
-
成员
t引用了本地范围的参数x,不是在main中定义的x。所以你有未定义的行为。 -
@G.M.对,但它不应该在第一次调用本身时给出随机值吗?因为该范围是直到构造函数调用?
-
未定义的行为——你不能期待任何事情。
-
@HemantKr 未定义行为就是这样,未定义。你可以得到任何输出,或者根本没有输出,你无法以任何方式预测或依赖它。
-
你能分辨出随机 20 和非随机 20 的区别吗?
标签: c++ constructor pass-by-reference pass-by-value