C++ 构造函数中的错误
C++ Errors in constructors
我的代码有问题。我有一个名为 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
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 模板,函数使用错误的构造函数来复制我的对象
- C++ OpenCV 卡尔曼滤波器构造函数错误
- 不命名构造函数和析构函数上的类型错误
- 处理简单 cpp 类构造函数中的错误
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 链接器错误:无法解析构造函数
- 当我尝试通过构造函数分配 char 数组时出现错误
- 没有参数的构造函数给我错误
- 使用复制构造函数的程序输出错误
- 默认构造函数上的分段错误
- 错误: 无效使用非静态数据成员"应用程序::应用程序构造函数"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 带有 QWidget 的分段错误构造函数.Qt/C++
- C++错误构造函数参数
- 错误:构造函数未命名类型
- 错误:构造函数在此上下文中受到保护
- 没有匹配的函数错误C++构造函数
- 错误:构造函数的多个定义