我试图使用一个在类中声明的枚举类型的类,如下所示:
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;
};
Run Code Online (Sandbox Code Playgroud)
我需要声明这个类的实例并初始化枚举类型.我来自C#并且通常看到枚举为类的OUTSIDE,而不是INSIDE就像它在这里一样.如何初始化枚举类型.例如,我想做这样的事情:
x myX(10);
myX.XEnumType = Linear;
Run Code Online (Sandbox Code Playgroud)
显然这不起作用.我该怎么做?
首先,您需要声明XEnumType类中类型的变量然后您可以使用范围的类名访问实际的枚举值:x::LINEAR或者x::DIPARABOLIC
class x{
//Your other stuff
XEnumType myEnum;
};
int main(void)
{
x myNewClass();
x.myEnum = x::LINEAR;
}
Run Code Online (Sandbox Code Playgroud)
第一:不要使用typedef.相反,将枚举的名称放在其头部
enum XEnumType {
LINEAR = 0, /// Perform linear interpolation on the table
DIPARABOLIC = 1 /// Perform parabolic interpolation on the table
};
Run Code Online (Sandbox Code Playgroud)
简而言之,像你一样做的行为大致相同,但在神秘的角落情况下会有所不同.您使用的语法与我上面仅在C中使用的语法非常不同.
第二:那只是定义一种类型.但是您想要定义该枚举的对象.这样做:
XEnumType e;
Run Code Online (Sandbox Code Playgroud)
综上所述:
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
用法:
x myX(10);
myX.my_enum = LINEAR;
Run Code Online (Sandbox Code Playgroud)