【问题标题】:C++ Errors in constructors构造函数中的 C++ 错误
【发布时间】:2014-02-14 20:59:55
【问题描述】:

我的代码有问题。 我有一个名为 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 Player team[x](firstName, lastName,birth)

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

【问题讨论】:

  • 请在此处发布您的代码。哪些错误让您感到困惑?
  • 我试过了。但是当我使用这个页面上的代码功能,然后复制我的代码时,它只是在 1 行左右放了一个代码 sn-p。我不喜欢复制我所有的台词。有没有更好的方法将代码复制到此页面?
  • @user3194111 选择代码,复制,到这里,粘贴,调整缩进。查看帮助选项以获取有关格式化的信息。
  • 选择代码-> Ctrl+K

标签: c++ arrays constructor


【解决方案1】:

这一行根本无效:

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

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

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

当然,当您首先创建数组时,您已经创建了一堆(默认初始化)。由于这是 C++,请使用 std::vector&lt;Player&gt;


另外,一些错误但没有产生错误:

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

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

【讨论】:

  • 谢谢。我从来没有使用过向量,这就是原因。我会四处搜索并寻找它。谢谢
【解决方案2】:

您的代码的一个问题是变量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

【讨论】:

  • “发生这种情况是因为您试图分配一个整数数组,其中包含尚未定义的变量匹配项。” - 这不是真的。 matches 未初始化并且具有不确定的值,读取它是 UB,但这不是编译器错误。大小错误来自这一行-Player team[x](firstName, lastName, birth);
  • @EdS。感谢您指出了这一点。我修改了我的条目以反映您的更正。
  • 好的。播放器构造函数现在可以工作了。现在的问题是 - 正如你所提到的 - int dates[matches]。我的想法是将 int* dates = new int[matches] 放在 sas >> 匹配下面的行;然而,这并没有奏效。我遇到了一些链接错误
  • @user3194111:sas的类型是什么?
猜你喜欢
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多