[英]C++ constructor initialization reference assignment
I am sure this question has been asked before. 我确信之前已经提出过这个问题。 But I cannot seem to find the exact answer that I am looking for. 但我似乎无法找到我正在寻找的确切答案。 Basically I am trying to create an object of the class as a member of the other class and pass one of the members by reference to the owned object through the constructor. 基本上我试图创建一个类的对象作为另一个类的成员,并通过构造函数引用所拥有的对象传递其中一个成员。 Sometimes this seems to work, other times I get a random value. 有时这似乎有效,有时我得到一个随机值。
I think that I am not understanding some rudimentary rule of initialization order 我认为我不理解初始化顺序的一些基本规则
Here is the code example: 这是代码示例:
class Foo
{
public:
Foo();
private:
int b;
Bar c;
};
class Bar
{
public:
Bar(int& parm);
private:
int& b_ref;
};
Foo::Foo(): b(0), c(b)
{}
Bar::Bar(int& parm): b_ref(parm)
{}
What I want is for c to own a reference to b and be able see the value as it changes. 我想要的是让c拥有对b的引用,并且能够在它改变时看到值。
Should I not use the initialization list in this case? 在这种情况下我不应该使用初始化列表吗?
The rule is that objects are initialised in the order of their declaration in the class
. 规则是对象按照它们在class
声明的顺序初始化。 In this case, it means that b
is initialised before c
, so this code should always work correctly. 在这种情况下,这意味着b
在c
之前初始化,因此此代码应始终正常工作。
If you swapped the order of the b
and c
members, then the int
referenced by param
would not yet be initialised in the constructor of Bar
. 如果交换了b
和c
成员的顺序,那么param
引用的int
将不会在Bar
的构造函数中初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.