-1

在 C++ 中使用enum时如何创建 getter 和 setter?

例子:

enum class FieldLayerStates
{
        kEmpty = 0, // new to the game.
        kActive = 1, // has fields already in the same.
        kAdd = 2 // field layer is ready to have a field added.
};

FieldLayerStates _fieldLayerState;

inline FieldLayerStates getFieldLayerState() { return _fieldLayerState; };

inline void setFieldLayerState(FieldLayerStates i) { _fieldLayerState = i; };

我在内联函数中遇到错误:

: Unknown type name 'FieldLayerStates'
: Cannot initialize return object of type 'int' with an lvalue of type 'FieldLayer::FieldLayerStates'

当我去使用它时:

 // check the status of the layer to see if it has fields in it already (loaded from CCUserDefaults
if (getFields().empty())
{
    // nothing, this must be our first time in.
    setFieldLayerStatus(kEmpty);
}

它说kEmpty是未声明的。

有人可以帮我解决我的困惑吗?

4

3 回答 3

4

您正在使用enum class,您确定这是您想要的吗?

如果您停止这样做,您的代码将起作用。

否则引用FieldLayerStates::kEmpty(因为 an 的枚举数enum class必须由它们的类型名称限定)

我不知道你为什么会收到Unknown type name 'FieldLayerStates'错误,因为你没有显示足够的上下文来理解代码,我猜我会说你正在尝试在类之外定义函数,你需要说FieldLayer::FieldLayerStates

请显示完整的代码,以便我们有机会看到您真正编译的内容。

于 2013-06-11T17:27:51.750 回答
1

我想你只是想要这个

enum FieldLayerStates
{
    kEmpty = 0, // new to the game.
    kActive = 1, // has fields already in the same.
    kAdd = 2 // field layer is ready to have a field added.
};
于 2013-06-11T17:27:06.570 回答
1
enum class Foo

是一个新的 C++11 语言特性,意思是“强类型和范围”枚举。它与仅仅显着不同

enum Foo

当您使用强类型枚举时,您必须使用它们所包含的范围来限定它们。

enum class Colors { Red, Green, Blue };
enum class Moods  { Happy, Bored, Blue };

没有“类”,这将无法编译,因为您已经定义了两次“蓝色”。使用“类”,您实际上已经定义了两个范围,它们具有自己的私有范围枚举,需要“::”运算符才能访问。

“类”也是强类型的,这意味着它们不会强制转换 - 例如转换为整数类型 - 除非您显式强制转换它们。

enum COLORS { RED, GREEN, BLUE };
enum class Colors { Red, Green Blue };

int i = RED; // Legal
Colors j = Colors::Red; // Legal
int i = Colors::Red; // Illegal: Colors::Red is not an integer, it's a Colors.
Colors j = Red; // Illegal: You didn't specify the scope.
Colors j = RED; // Illegal: RED is an integer, not a Colors.

for (int i = RED; i <= BLUE; ++i) { cout << i << endl; } // Legal
// But Colors is not a numeric type, you can't do math or increment on it,
// so the following is illegal:
for (auto j = Colors::Red; j <= Colors::Blue; ++j)

enum class Flags = { Herp = 1, Derp = 2 };
Flags combo = Flags::Herp;
combo |= Flags::Derp; // Illegal, no '|' operator for Flags, casting required.
于 2013-06-11T19:53:20.830 回答