c++ - 初始化引用成员:语法不同的原因

标签 c++ constructor reference initialization

我有两个类,其中一个具有作为引用成员的另一个对象:

class myClass{
public:
    myClass() { };
};

class mySecondClass {
public:
    mySecondClass(myClass& reference)
    {
        myClassReference = reference; //doesn't get accepted by the compiler
    };

    myClass& myObjectReference;
};

我发现了(感谢Passing by reference to a constructor
),即mySecondClass(myClass& reference) : myObjectReference(reference){};完成了这项工作。

但是,为什么我不能使用myObjectReference = reference;呢?

最佳答案

这是因为{ myClassReference = reference; }被视为
分配给应该已经初始化的东西。

成员初始化列表: member1{value1}, member2{value2}...旨在提供初始值(不应该
之前有效)。

对于引用的特定情况,情况与

int i=4;
int &r=i; // the reference is initialised (alias for i)
r=5;      // the reference itself is not changed but
          //   the referenced object (i) is assigned

关于c++ - 初始化引用成员:语法不同的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60980728/

相关文章:

javascript - 将字符串参数传递给构造函数以调用函数

java - 如何为井字游戏逻辑引用 JButtons 对象(Java 中的井字游戏)

perl - 如何将子例程调用的结果分配给 Perl 中的数组引用?

c++ - stdio.h 头文件的详细引用

C++ 图实现

c++ - 使部分代码中的变量不可用

c++ - 事件处理程序未被调用? - wxWidgets

c++ - 如何将 graphviz 与 VIsual C++ 链接

java - 静态方法(main)如何能够捕获非静态方法(构造函数)并执行它?

Javascript 对象构造函数作为另一个对象的方法