C ++枚举和内联头函数

时间:2013-06-11 17:24:52

标签: c++ c++11 enums compiler-errors

在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未声明。

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

3 个答案:

答案 0 :(得分:4)

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

如果你停止这样做,你的代码就会起作用。

否则请参考FieldLayerStates::kEmpty(因为enum class的枚举数必须按其类型名称限定)

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

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

答案 1 :(得分: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.
};

答案 2 :(得分:1)

enum class Foo

是一种新的C ++ 11语言功能,意思是“强类型和范围”枚举。它与

明显不同
enum Foo

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

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

没有“class”,这将无法编译,因为您已经定义了两次“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.