枚举应该按照您描述的方式工作。不幸的是,您只提供了修改过的、无法运行的代码,没有编译器错误或其他输出。但是,以下代码应该向您展示如何使用枚举:(现场演示)
#include <iostream>
enum Race { None, Living, Dead, Nature}; // always put invalid as the 0 entry.
class Player
{
uint32_t m_karma;
bool m_myTurn;
Race m_myRace;
public:
void addPlayer(int x_)
{
std::cout << "added player " << x_ << std::endl;
m_karma = 0;
m_myTurn = false;
m_myRace = None;
}
};
int main(int argc, const char** argv)
{
Player fred;
fred.addPlayer(1);
return 0;
}
如果您有一个支持 C++11 的编译器,您可以更具体并使用“枚举类”,这将强制您限定枚举(即 Race::None)。(现场演示)
#include <iostream>
enum class Race { None, Living, Dead, Nature}; // always but invalid as the 0 entry.
class Player
{
uint32_t m_karma;
bool m_myTurn;
Race m_myRace;
public:
void addPlayer(int x_)
{
std::cout << "added player " << x_ << std::endl;
m_karma = 0;
m_myTurn = false;
m_myRace = Race::None;
}
};
int main(int argc, const char** argv)
{
Player fred;
fred.addPlayer(1);
return 0;
}
"player[x].race = None" 不起作用,因为那是分配,而不是相等性的测试。你没有说它为什么不起作用,我会假设 - 如果它不仅仅是错误的变量名 - 因为它是私有的或不可访问的。在这种情况下,只需添加一个成员函数即可返回比赛:
class Player {
...
public:
Race getRace() const { return m_myRace; }
...
};