C++类内的枚举
Enums inside of a C++ class
我正在尝试使用一个在类中声明了枚举类型的类,如下所示:
class x {
public:
x(int);
x( const x &);
virtual ~x();
x & operator=(const x &);
virtual double operator()() const;
typedef enum {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
} XEnumType;
};
我需要声明此类的实例并初始化枚举类型。 我来自 C#,通常看到枚举声明在类的外部,而不是像这里那样在内部。 如何初始化枚举类型。 例如,我想做这样的事情:
x myX(10);
myX.XEnumType = Linear;
显然这是行不通的。 我该怎么做?
首先,您需要声明一个类型为类中XEnumType
的变量然后,可以使用作用域的类名访问实际枚举值:x::LINEAR
或x::DIPARABOLIC
class x{
//Your other stuff
XEnumType myEnum;
};
int main(void)
{
x myNewClass();
x.myEnum = x::LINEAR;
}
首先:不要使用 typedef
。相反,将枚举的名称放在其头部
enum XEnumType {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
};
简而言之,像你一样做的行为大致相同,但在神秘的角落情况下会有所不同。您使用的语法的行为将与我上面仅在 C 中使用的语法大不相同。
第二:这只是定义一个类型。但是,您希望定义该枚举的对象。这样做:
XEnumType e;
总结:
class x {
/* ... stays the same ... */
enum XEnumType {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
};
XEnumType e;
};
void someFunction() {
x myX(10);
myX.e = x::LINEAR;
}
enum XEnumType {
LINEAR, DIPARABOLIC
};
class x {
public:
x(int);
x( const x &);
virtual ~x();
x & operator=(const x &);
virtual double operator()() const;
XEnumType my_enum;
};
用法:
x myX(10);
myX.my_enum = LINEAR;
你声明了一个新类型:XEnumType
.您必须在类中创建该类型的字段x
。.例如:
class x {
public:
x(int);
x( const x &);
virtual ~x();
x & operator=(const x &);
virtual double operator()() const;
typedef enum {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
} XEnumType;
public:
XEnumType type;
};
然后,您可以通过以下方式访问它:
x foo(10);
foo.type = LINEAR;
行
typedef enum {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
} XEnumType;
定义了一个名为 XEnumType
的类型,实际上这无论如何都是多余的 - 更喜欢这样的东西:
enum XEnumType
{
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
};
现在,您需要在类中定义此类型的成员
XEnumType _eType;
在你的构造函数中,你可以初始化为任何
x::x(int ) : _eType(x::LINEAR) {}
让我先假设一些前提条件:
- 类
x
来自第三方库,因此无法更改。 - 类
x
在枚举的帮助下定义了一些整数常量。 - 类
x
应该用LINEAR
或DIPARABOLIC
中的一个常量进行初始化。
您的问题是这些常量值是在类 x
中声明的。因此,要初始化x
实例,您需要指定范围:
而不是
x myX(10);
myX.XEnumType = Linear;
尝试
x myX(x::LINEAR);
通过指定x::
,您可以提供常量的作用域。
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 访问在 C++ 结构中声明的枚举变量
- 枚举类'classname'的多重定义
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- typedef 枚举和枚举类有什么区别?
- 为什么我的开关/机箱在使用枚举时默认?
- 标准::可选枚举的比较运算符
- C++两个源文件之间共享的枚举的静态实例
- 打印没有铸件的枚举可以在C++中吗?
- 枚举成员与静态 int 成员?
- C++:枚举:错误:应使用标识符而不是"}"
- 带有 c++ 的枚举(输入检查)
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 为什么 int 类型的枚举类值不能用作 int
- 在 C++ 中输出枚举类类型的向量元素