每次尝试将另一个对象Hand
的实例声明为同一 header 和源文件上的另一个类的方法的参数时,都会遇到这些错误。
即使声明和实现语句相同。
错误:
Severity Code Description Project File Line Suppression State
Error (active) E0020 identifier "Hand" is undefined Risk
C:\Users\ebrah\source\repos\Risk\Risk\Risk\Cards.h 44
Severity Code Description Project File Line Suppression State Error (active)
E0147 declaration is incompatible with "void Deck::draw(<error-type> &hand)"
(declared at line 44 of "C:\Users\ebrah\source\repos\Risk\Risk\Risk\Cards.h")
Risk C:\Users\ebrah\source\repos\Risk\Risk\Risk\Cards.cpp 186
我的代码:在头文件中:
class Card {
private:
static unsigned int nextCardID;
unsigned int cardID;
CardType cardType;
public:
Card();
~Card();
//Card(const Card &card);
Card(CardType armyType);
CardType getArmyType() const;
void setArmyType(CardType &armytype);
int getCardID() const;
void play(list<Card*> handCards, CardType& card);
friend ostream& operator<<(ostream& strm, const Card& card);
};
class Deck{
private:
list<Card> allCards;
list<Card*> deckCards;
void generateCard(int numberOfCounteries);
public:
Deck();
~Deck();
Deck(int numberOfCounteries);
void draw(Hand& hand);
friend ostream& operator<<(ostream& strm, const Deck& deck);
list<Card> getAllCards() const;
void setAllCards(list<Card> allCards);
list<Card*> getDeckCards() const;
void setDeckCards(list<Card*> deckCards);
};
class Hand {
private:
list<Card*> handCards;
public:
Hand();
~Hand();
friend ostream& operator<<(ostream& strm, const Hand hand);
list<Card*> getHandCards() const;
void setHandCards(list<Card*> handCards);
};
在源文件中:void Deck::draw(Hand& hand)
{
}
我也想知道如何返回对
list
的引用。谢谢。
最佳答案
您可以在Hand
类的定义之前forward declare Deck
:
class Hand; //<-- here
class Deck{
private:
list<Card> allCards;
list<Card*> deckCards;
void generateCard(int numberOfCounteries);
public:
Deck();
~Deck();
Deck(int numberOfCounteries);
void draw(Hand& hand);
friend ostream& operator<<(ostream& strm, const Deck& deck);
list<Card> getAllCards() const;
void setAllCards(list<Card> allCards);
list<Card*> getDeckCards() const;
void setDeckCards(list<Card*> deckCards);
};
//...
要返回对list
的引用,只需将&
添加到方法中,即:list<Card>& getAllCards() const;
请注意,这是一个const
引用,您无法在调用方中更改list
,这是一个好习惯,如果您想访问数据而不更改它,则可以避免通过复制返回的开销。如果您想更改
list
,则需要删除const
关键字。