C++类内的枚举

Enums inside of a C++ class

本文关键字:枚举 C++      更新时间:2023-10-16

我正在尝试使用一个在类中声明了枚举类型的类,如下所示:

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::LINEARx::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 应该用 LINEARDIPARABOLIC 中的一个常量进行初始化。

您的问题是这些常量值是在类 x 中声明的。因此,要初始化x实例,您需要指定范围:

而不是

x myX(10);   
myX.XEnumType = Linear;

尝试

x myX(x::LINEAR);

通过指定x::,您可以提供常量的作用域。