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 那么如何通过 inGame 默认构造函数进行初始化?它会在构造函数中写入吗?

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 {”之后有一个错误,即“期望一个 )”。而 m1 { "}<--" 表示“期望一个 ;”

4

2 回答 2

5

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

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

无论是常规数组、 、 还是任何其他序列容器,这都可以std::array使用std::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 回答