c++ - Why can an enumeration inside class A (public) be accessed in class B using scope operator and class A name?
问题描述
as you can see in the code, enum CardSuit
is not static
I don't understand how Deck
constructor can directly access MAX_SUITS
in this line of code:
for (int suit = 0; suit < Card::MAX_SUITS; ++suit)
Shouldn't an object of class Card
be needed for class Deck
to access MAX_SUITS
?
something like:
Card card1;
for (int suit = 0; suit < card1::MAX_SUITS; ++suit)
If I declare int x;
in Class Card and say Card::x
inside definition of class Deck
, then I get an error saying "improper use of non-static member". I was expecting to get the same error for usage of Card::MAX_SUITS
too, but that does not seem to be the case, it works fine.
Here is the relevant part of the program:
class Card
{
public:
enum CardSuit
{
SUIT_CLUB,
SUIT_DIAMOND,
SUIT_HEART,
SUIT_SPADE,
MAX_SUITS
};
enum CardRank
{
RANK_2,
RANK_3,
RANK_4,
RANK_5,
RANK_6,
RANK_7,
RANK_8,
RANK_9,
RANK_10,
RANK_JACK,
RANK_QUEEN,
RANK_KING,
RANK_ACE,
MAX_RANKS
};
private:
CardRank m_rank;
CardSuit m_suit;
public:
Card(CardRank rank=MAX_RANKS, CardSuit suit=MAX_SUITS) :
m_rank(rank), m_suit(suit)
{
}
int getCardValue() const
{
switch (m_rank)
{
case RANK_2: return 2;
case RANK_3: return 3;
case RANK_4: return 4;
case RANK_5: return 5;
case RANK_6: return 6;
case RANK_7: return 7;
case RANK_8: return 8;
case RANK_9: return 9;
case RANK_10: return 10;
case RANK_JACK: return 10;
case RANK_QUEEN: return 10;
case RANK_KING: return 10;
case RANK_ACE: return 11;
}
return 0;
}
};
class Deck
{
private:
std::array<Card, 52> m_deck;
public:
Deck()
{
int card = 0;
for (int suit = 0; suit < Card::MAX_SUITS; ++suit)
for (int rank = 0; rank < Card::MAX_RANKS; ++rank)
{
m_deck[card] = Card(static_cast<Card::CardRank>(rank), static_cast<Card::CardSuit>(suit));
++card;
}
}
};
解决方案
枚举是类型,而不是成员变量。因此,如果它们是public:
,则可以访问它们;范围运算符将类视为附加限定符。
推荐阅读
- c - 使用 C 语言计算该短语中每个单词的出现次数
- reactjs - 将下拉组件添加到材料表操作
- python - 如果数据框中字符串的第 n 个字符是某个字符,则删除该行
- javascript - 如何在Javascript中确定数组对象中的前2条记录
- php - 如何处理 .env 变量中的 %kernel.project_dir%?
- javascript - 如何设置侧导航栏菜单的活动类?
- vba - dbOpenDynaset - '对象变量或未设置块变量'
- pandas - 带有 2 个参数的 Pandas 函数来查找阈值
- json - 读取 Pyspark Struct Json 列非必需元素
- powerbi - 在 Power Bi 中,如何创建一个度量,给出表格视觉中的行数