<分区>
我对 C++ 中的引用初始化感到困惑。 通常引用应该在声明时被初始化,但我发现当它是一个类成员时,引用被声明而没有被初始化。
是特例吗?
什么是正确的规则?
<分区>
我对 C++ 中的引用初始化感到困惑。 通常引用应该在声明时被初始化,但我发现当它是一个类成员时,引用被声明而没有被初始化。
是特例吗?
什么是正确的规则?
最佳答案
这个规则仍然适用,作为成员变量引用你必须在构造函数的初始化列表中初始化。示例:
class X {
public:
X(int& ri) : mri(ri) {}
// X() {} // ERROR! no explicit initialization of mri
int& mri;
};
int main() {
int i;
X x(i);
}
如果不初始化它,您将遇到编译错误。
(我决定从评论中总结其他好的说明,使这个答案更有用)
根据标准 8.5.3/3(强调我的):
The initializer can be omitted for a reference only in a parameter declaration (8.3.5), in the declaration of a function return type, in the declaration of a class member within its class definition (9.2), and where the extern specifier is explicitly used.
所以下面的代码只是struct X
的定义,其中只声明了mri
变量。
struct X {
int &mri; // declaration of mri (ERROR if you define variable of this struct)
};
在您创建(定义)X 类型的对象之前,编译器不会显示任何错误。当你写:
int main() {
X x; // error, `x.r` is not bound to any object
}
编译器会报错,这是因为你已经定义了 x
并且这是你还必须将 x.r 绑定(bind)到某个对象的地方。唯一可以这样做的地方是在构造函数初始化列表中。
您可能还会注意到,当您将引用添加为非静态数据成员时,编译器会将(除其他外)默认构造函数标记为已删除。
关于C++ 引用初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38953734/