2014-02-14 85 views
0

我的代码有问题。 我有一个所谓的播放器类,它看起来像这样构造函数中的C++错误

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

我要创建5倍Player团队[X](名字,姓氏,出生)

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

+0

请在这里发表您的代码。哪些错误令你感到困惑? –

+0

我试过。但是,当我在此页面上使用代码功能,然后复制我的代码时,它只会将代码片段放在1行左右。我不喜欢复制我所有的线条。有没有更好的方法将代码复制到此页面? – Snigelmat

+0

@ user3194111选择代码,复制到这里,粘贴,调整缩进。查看有关格式化信息的帮助选项。 – crashmstr

回答

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

+0

谢谢。我从来没有使用过载体,这就是为什么。我会谷歌周围并寻找它。谢谢 – Snigelmat

0

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

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

你应该调用new int[matches]前初始化matches。当你分配的Players阵列

一个nrOfPlayersteam玩家构造:

Player* team = new Player[nrOfPlayers]; 

您可以在一个球员的信息通过创建临时Player对象和team其分配给一个元素现在填写。这将调用Player的隐含定义拷贝赋值运算符

替换线与75:

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

“发生这种情况是因为您试图分配一个整数数组与变量匹配尚未定义。” - 这不是真的。 'matches'未初始化并且具有不确定的值,并且读取它是UB,但这不是编译器错误。大小错误来自这一行 - Player team [x](firstName,lastName,birth);' –

+0

@EdS。感谢您指出了这一点。我修改了我的参赛作品以反映您的更正。 – Anachronous

+0

好的。玩家构造函数现在可以工作。现在的问题是 - 如你所说 - int日期[matches]。我的想法是把int * dates = new int [matches]放在sas >> matches下;但是,这并不奏效。我有一些链接错误 – Snigelmat