C++ 引用初始化

标签 c++ reference

<分区>

我对 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/

相关文章:

android - 指示 gnu make 仅使用静态库

c++ - 防止 QDockWidget 自动调整大小行为

c++ - 如何确保我的 makefile 检测到头文件和 cpp 文件中的更改?

c++ - 构造函数初始化行为

c# - 需要一些关于引用类型的说明

c++ - Windows 10 中的 Windows 服务安装/卸载

java - 引用封闭对象通过匿名类转义-java

java - 需要像指向 JTable (Java) 的指针之类的东西

c# - 非静态字段、方法或属性需要对象引用?

c++ - "A reference may be bound only to an object",为什么 "const int &ref = 3;"有效?