使用 enum
时在 C++ 中如何创建 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
未声明。有人可以帮我解决我的困惑吗?
最佳答案
您正在使用 enum class
,你确定这是你想要的吗?
如果您停止这样做,您的代码将起作用。
否则请参阅 FieldLayerStates::kEmpty
(因为 enum class
的枚举数必须由它们的类型名称限定)
我不知道你为什么得到 Unknown type name 'FieldLayerStates'
错误,因为您没有显示足够的上下文来理解代码,我猜我会说您正在尝试定义类之外的函数,您需要说 FieldLayer::FieldLayerStates
请出示已满 代码,所以我们有机会看到你真正在编译什么。
关于C++ 枚举和内联 header 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17050138/