【发布时间】:2013-03-14 07:51:42
【问题描述】:
考虑下面的 C++ 代码:
#include<iostream>
using namespace std;
class Test {
int &t;
public:
Test (int &x) { t = x; }
int getT() { return t; }
};
int main()
{
int x = 20;
Test t1(x);
cout << t1.getT() << " ";
x = 30;
cout << t1.getT() << endl;
return 0;
}
使用 gcc 编译器时出现以下错误
est.cpp: In constructor ‘Test::Test(int&)’:
est.cpp:8:5: error: uninitialized reference member ‘Test::t’ [-fpermissive]
为什么编译器不直接调用构造函数?
【问题讨论】:
-
虽然答案解释了如何解决这个问题,但我想指出根本问题是初始化实际上发生在 输入构造函数的主体之前,以确保所有成员在使用前都处于有效状态。由于引用必须被初始化,并且在初始化后不能被“重新定位”,所以在输入构造函数的主体之前,它们在逻辑上也需要指向一个实际的变量。
标签: c++ oop class-members