0

ゲーム オブジェクトを制御するためのメイン クラスが「inGame」であるゲームを作成しています。「inGame」内に構成された他のいくつかのカスタムメイドのクラスがあります。

お気に入り、

class mouse
{
  int x, y;
  bool alive;
  float speed;
  public:
    mouse(int xx, int yy, float spd, bool alv)
    {
        x = xx; y = yy; speed = spd; alive = alv;
    }
    // member functions
};

class inGame
{
  mouse m1; 
  dog d1; // single object which are easy to construct
  public:
    inGame() : d1(200, 400, 1.5, false), m1(40, 40, 0.5, false) //This works fine
    {} //coordinates fixed and set by me
    // member functions
};

しかし今、私は 3 匹のマウスが欲しいとしましょう。だから私はm1 [3]またはおそらくベクトルを考えました。

class inGame
{
  mouse m1[3]; // like i want 3 mouse(animals) in the game screen
  dog d1; // single object which are easy to construct
  public:
    inGame() : d1(200, 400, 1.5, false) //Confusion here m1(40, 40, 0.5, false)
    {}
    // members
};

だから私は次のことを試しました:

inGame() : m1[0](1,2,3,true), m1[1](2,3,4,true), m1[2](3,4,5,true) { } //NO
inGame() : m1 { (1,2,3,true), (2,3,4,true), (3,4,5,true) } { } //NO
inGame() : m1 { (1,2,3,true), (2,3,4,true), (3,4,5,true); } { }

std::vector m1 を使用する場合でも、ゲーム内のデフォルト コンストラクターを使用して初期化する方法を教えてください。コンストラクター内に書いているでしょうか?

mouse temp(1,2,3,true);
m1.push_back(temp);

より良いアプローチはどれですか?主に私はただやります:

inGame GAME; //Just to construct all animals without user requirement

ありがとう。

アップデート:

運が悪い

inGame() : m1 { mouse(1,2,3,true), mouse(2,3,4,true), mouse(3,4,5,true) } { }
inGame() : m1 { {1,2,3,true}, {2,3,4,true}, {3,4,5,true} } { }

"m1 {" の後に "expected a )" というエラーがあります。そして m1 { "}<--" は ";" を期待していました

4

2 に答える 2

5

C++11 以降を使用していると仮定すると、

inGame() : m1{{1,2,3,true}, {2,3,4,true}, {3,4,5,true}}
{}

これは、通常の配列、std::arraystd::vector、またはその他のシーケンス コンテナーのいずれであっても機能します。

古代の方言に固執している場合、初期化はより問題になります。ベクトルを使用し、説明したようにコンストラクターを呼び出すpush_backことは、おそらく最も厄介なアプローチです。mouse配列を使用するには、デフォルトのコンストラクターを指定してから、コンストラクターの各要素を再割り当てする必要があります。

于 2014-04-28T16:15:54.737 に答える
4

ブレースで囲まれた初期化子を使用する必要があります。

inGame() : m1 { {1,2,3,true}, {2,3,4,true}, {3,4,5,true} } { } 

C++11 を使用しない場合は、次のようなコンテナーを使用しstd::vector<mouse>てコンストラクターの本体内に配置するか、適切に初期化されたものを返す関数を使用する必要があります。

std::vector<mouse> make_mice()
{
  std::vector<mouse> v;
  v.reserve(3);
  v.push_back(mouse(1, 2, 3, true));
  v.push_back(mouse(2, 3, 4, true));
  v.push_back(mouse(3, 4, 5, true));
  return v;
}

それから

inGame() : m1(make_mice()) {}

m1今はどこですかstd::vector<mouse>

于 2014-04-28T16:16:12.497 に答える