我的代码出了问题。 我有一个名为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)
但这是我得到错误的地方。有什么建议吗?
答案 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
数组时,nrOfPlayers
个Players
玩家会被构建:
Player* team = new Player[nrOfPlayers];
您现在可以通过创建临时Player
对象并将其分配给team
中的元素来填写玩家的信息。这将调用Player
隐式定义的复制赋值运算符:
将第75行替换为:
team[x] = Player(firstName, lastName, birth); // copy constructor is called