构造函数中的C ++错误

时间:2014-02-14 20:59:55

标签: c++ arrays constructor

我的代码出了问题。 我有一个名为Player的类,看起来像这样

class Player
{
public:
   ...
Player();
Player(string firstName, string lastName, int birthYear);
~Player();
   ...
};

我的source.cpp看起来像这样

string firstName = ...;
string lastName = ...;
int birth = ...

Player team[x](firstName, lastName, birth); // <--- This is were I get my errors

我的错误在说

error C3074: an array can only be initialized with an initializer-list

error C2466: cannot allocate an array of constant size 0

error C2057: expected constant expression

我想要使用的构造函数是Player(string firstName, string lastName, int birthYear)。我想我可能正在使用source.cpp中的默认构造函数

我想创建5x玩家团队[x](firstName,lastName,birth)

但这是我得到错误的地方。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

此行无效:

Player team[x](firstName, lastName, birth); // <--- This is were I get my errors

没有意义。您正在尝试声明一个数组并同时调用构造函数。您已经创建了team数组。如果您想创建Player并分配它,那么您将使用:

team[x] = Player(firstName, lastName, birth);

当然,在第一次创建数组时,您已经创建了一堆(默认初始化)。由于这是C ++,请使用std::vector<Player>


此外,出了问题,但没有产生错误:

int matches;
int* dates = new int[matches];

此处,matches未初始化且其值不确定。读取该变量会调用未定义的行为,当然你不希望你的数组有任何随机大小(为什么你不再使用向量?)你需要在使用之前初始化matches

答案 1 :(得分:0)

您的代码存在的一个问题是变量matches尚未初始化且具有不确定的值。

int matches;
int* dates = new int[matches];

您应该在致电matches之前初始化new int[matches]

当您分配team数组时,nrOfPlayersPlayers玩家会被构建:

Player* team = new Player[nrOfPlayers];

您现在可以通过创建临时Player对象并将其分配给team中的元素来填写玩家的信息。这将调用Player隐式定义的复制赋值运算符

将第75行替换为:

team[x] = Player(firstName, lastName, birth); // copy constructor is called