2

たとえば、次のコードがあるとします。

class Foo
{
    public:
    Foo(int x) : _foo(x)
    {

    }

    private:
    int _foo;

    protected:
    std::string _bar;
};

class Bar : public Foo
{
    public:
    Bar() : Foo(10), _temp("something"), _bar("something_else")
    { 

    }
    private:
    std::string _temp;
};

int main()
{
    Bar stool;
}

_bar はクラス Foo であり、それが存在することを認識していないように見えるため、コードは実行されません。それとも、Foo のコンストラクターに _bar を入れますか? これは機能しますが、_bar に常に何かを割り当てる必要がない場合はどうでしょうか?

編集:以下は私が使用していた実際のコードです。

Entity::Entity(GameState *state, bool collidable) 
    :_isLoaded(false), _state(state), alive(true), collidable(collidable),               name(entityDetault)

{

}

Entity::Entity(GameState *state, bool collidable, entityName _name)
    :_isLoaded(false), _state(state), alive(true), collidable(collidable), name(_name)
{

}

子クラスはこのコンストラクターを使用します。

Player::Player(GameState *state) 
: Entity(state,true,entityName::entityPlayer), health(100),bulletSpeed(600),_colour(sf::Color(128,255,86,255))

これはすべて正しいように見えますか?コンストラクター本体ですべてを行うよりもわずかに優れています。

4

4 に答える 4

5

クラスのコンストラクターのメンバー初期化子リストは、次のC初期化のみを行うことができます。

  • の直接基底クラスC
  • の直接のメンバーC
  • の仮想基本クラスC (あまり頻繁には出てきません)

基本クラスのメンバーを初期化する唯一の方法は、基本クラスのコンストラクターを使用することです。Cまたは、初期化を控えてから、のコンストラクターの本体で代入を行います。ただし、後者はメンバーまたは参照には使用できずconst、一般に初期化と同じことはしません。

于 2013-03-23T14:51:12.447 に答える
2

初期化子リストから本体に移動することもできます (const でない場合)。

Bar() : Foo(10), _temp("something")
{
    _bar = "something_else";
}

または、次の 2 番目の (おそらく保護された) コンストラクターを提供しFooます。

class Foo
{
public:
    Foo(int x) : _foo(x)
    {

    }

protected:
    Foo(int x,std::string s) : _foo(x), _bar(s)
    {
    }

private:
    int _foo;

protected:
    std::string _bar;
};

class Bar : public Foo
{
public:
    Bar() : Foo(10,"something_else"), _temp("something")
    { 

    }

private:
    std::string _temp;
};
于 2013-03-23T14:52:19.890 に答える
1

アクセスする前に、基本クラスを初期化する必要があります。基本クラスでメンバー変数を初期化する場合は、そのメンバーを初期化する基本クラス コンストラクターを呼び出して行う必要があります。

于 2013-03-23T14:51:18.697 に答える
1

のコンストラクタの初期化リスト_barを入れることができます。常に何かを割り当てる必要がないFoo場合は、デフォルト値を使用できます。_bar

class Foo
{
public:
   Foo(int x):_foo(x)
   {
   }
protected:
   Foo(int x, string s) : _foo(x),_bar(s)
   {

   }

private:
   int _foo;

protected:
   std::string _bar;
};

class Bar : public Foo
{
public:
   Bar() : Foo(10,"something else"), _temp("something")
   { 

   }
private:
  std::string _temp;
};
于 2013-03-23T14:52:52.267 に答える