在下面的代码中,我尝试在void Player::chooseDiscard
中将Card类的丢弃值分配给同一类的throwsList数组,但是编译器将其识别为undefined reference to 'Player::discardList'
。如何防止此错误?
class Player
{
public:
Player();
virtual void chooseDiscard(int);
void replenish( );
vector<Card>allCards;
friend ostream& operator<<(ostream& os, Card hand);
int selfIndex; //index within player vector, starting with 0 for the human
vector<Card>hand; //holds 7 cards
protected:
int takeFrom; //player supplying new Car
Card discard; //card being discarded
int discardIndex; //position within hand of card being discarded
static Card discardList[];
};
void Player::chooseDiscard(int number)
{
discard = hand[number-97];
discardIndex = number-97;
discardList[selfIndex] = discard;
}
最佳答案
好吧,您已将discardList
声明为Player
类的静态数据成员,但是通过这样做,您并未对其进行定义。
C++ ISO标准对此进行了以下说明:
因此,编译器(实际上是抱怨的链接器)正确地报告了 undefined reference ,因为从未定义discardList
。
您应该做的是离线定义discardList
,并在Player
类的范围内进行定义,例如:
Card Player::discardList[] = {/* PUT SOME Card objects IN HERE*/};
使用C数组的大小是固定的,因此可能会受到严格限制,但是,如果您知道
discardList
永远不会增长或缩小,它也可能非常有效。否则,std::vector是更好的选择。