如何在另一个类中初始化我的对象数组

TRE*_*MOR 0 c++ class initialization-list

我正在制作一个游戏,其中我控制游戏对象的主要类是"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
};
Run Code Online (Sandbox Code Playgroud)

但现在可以说我想要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
};
Run Code Online (Sandbox Code Playgroud)

所以我尝试了以下内容:

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); } { }
Run Code Online (Sandbox Code Playgroud)

即使我使用std :: vector m1然后如何通过inGame默认构造函数初始化?它会在构造函数内写吗?

mouse temp(1,2,3,true);
m1.push_back(temp);
Run Code Online (Sandbox Code Playgroud)

哪种方法更好?在主要我会做:

inGame GAME; //Just to construct all animals without user requirement
Run Code Online (Sandbox Code Playgroud)

谢谢.

更新:

没有运气

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} } { }
Run Code Online (Sandbox Code Playgroud)

在"m1 {"之后出现"期望a)"的错误.并且m1 {"} < - "表示"预期a;"

Mik*_*our 5

假设您使用的是C++ 11或更高版本,

inGame() : m1{{1,2,3,true}, {2,3,4,true}, {3,4,5,true}}
{}
Run Code Online (Sandbox Code Playgroud)

这将工作无论是规则的阵列,std::array,std::vector,或任何其它序列容器.

如果你坚持使用古老的方言,那么初始化将更成问题.使用向量,并push_back在您描述的构造函数中调用,可能是最不讨厌的方法.要使用数组,您需要提供mouse默认构造函数,然后重新分配构造函数中的每个元素.