如何初始化一个类的引用成员变量?
考虑以下代码C ++:
Consider the following code 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编译器时显示以下错误
It is showing the following error while using gcc compiler
est.cpp: In constructor ‘Test::Test(int&)’:
est.cpp:8:5: error: uninitialized reference member ‘Test::t’ [-fpermissive]
为什么编译器不直接调用构造函数?
Why doesn't the compiler directly call the Constructor?
这是因为只能在初始化列表中初始化引用.使用
That is because references can only be initialized in the initializer list. Use
Test (int &x) : t(x) {}
说明:引用只能设置一次,发生此情况的地方是初始化列表.完成之后,您将无法设置引用,而只能将值分配给引用的实例.您的代码意味着,您尝试向引用的实例分配某些内容,但是该引用从未初始化,因此它没有引用任何int
实例,您会收到错误.
To explain: The reference can only be set once, the place where this happens is the initializer list. After that is done, you can not set the reference, but only assign values to the referenced instance. Your code means, you tried to assign something to a referenced instance but the reference was never initialized, hence it's not referencing any instance of int
and you get the error.