gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:13:20 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com