如何访问其他 类 的成员枚举 (c++)
How to access member enum's of other classes (c++)
我需要访问属于另一个 class 的 public 枚举,为了简化,像这样:
class obj
{
public:
enum Type
{
t1,
t2,
t3
};
Type type;
};
class otherObj
{
public:
void setType(obj* o);
};
void otherObj::setType(obj* o)
{
o->type = obj::Type::t1;
return;
}
我该怎么做,因为行
o->type = obj::Type::t1;
抛出错误:
obj::Type is not a class or namespace.
obj::t1
obj::t2
obj::t3
C++ 枚举不是很棒吗?即使枚举可以被视为一种类型,这些值也属于它们之上的范围。
你要么只使用
obj::t1;
或在 enum
声明中指定 class
attribute
enum class Type {
t1,
t2,
t3
};
在 C++03 中,枚举值属于封闭范围。因此,将 obj::Type::t1
替换为 obj::t1
对您有用。
这有点违反直觉,并由 C++11 中的 enum class
功能解决,它将枚举值直接放在枚举范围内。因此,如果您在 C++11 兼容编译器中使用 enum class
,那么您将能够像您当前所做的那样使用 obj::Type::t1
。
我需要访问属于另一个 class 的 public 枚举,为了简化,像这样:
class obj
{
public:
enum Type
{
t1,
t2,
t3
};
Type type;
};
class otherObj
{
public:
void setType(obj* o);
};
void otherObj::setType(obj* o)
{
o->type = obj::Type::t1;
return;
}
我该怎么做,因为行
o->type = obj::Type::t1;
抛出错误:
obj::Type is not a class or namespace.
obj::t1
obj::t2
obj::t3
C++ 枚举不是很棒吗?即使枚举可以被视为一种类型,这些值也属于它们之上的范围。
你要么只使用
obj::t1;
或在 enum
声明中指定 class
attribute
enum class Type {
t1,
t2,
t3
};
在 C++03 中,枚举值属于封闭范围。因此,将 obj::Type::t1
替换为 obj::t1
对您有用。
这有点违反直觉,并由 C++11 中的 enum class
功能解决,它将枚举值直接放在枚举范围内。因此,如果您在 C++11 兼容编译器中使用 enum class
,那么您将能够像您当前所做的那样使用 obj::Type::t1
。