C++ 构造函数中的错误

C++ Errors in constructors

本文关键字:错误 构造函数 C++      更新时间:2023-10-16

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

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

我的来源.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) .我认为我可能在源代码中使用默认构造函数.cpp

我想创建 5x 玩家团队[x](名字、姓氏、出生)

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

此行根本无效:

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,然后再使用它。

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

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

您应该在调用 new int[matches] 之前初始化matches

分配

Players数组时,将构造nrOfPlayers玩家的team

Player* team = new Player[nrOfPlayers];

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

将第 75 行替换为:

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