1

私はこの質問が以前に尋ねられたと確信しています。しかし、探している正確な答えを見つけることができないようです。基本的に、クラスのオブジェクトを他のクラスのメンバーとして作成し、コンストラクターを介して所有オブジェクトへの参照によってメンバーの1つを渡そうとしています。これが機能しているように見えることもあれば、ランダムな値を取得することもあります。

初期化順序の基本的なルールを理解していないと思います

コード例は次のとおりです。

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)
{}

私が望むのは、c が b への参照を所有し、値の変化に応じて値を確認できるようにすることです。

この場合、初期化リストを使用すべきではありませんか?

4

1 に答える 1

3

The rule is that objects are initialised in the order of their declaration in the class. In this case, it means that b is initialised before c, so this code should always work correctly.

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.

于 2013-03-18T04:43:05.407 に答える