Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums inside of a C++ class

Tags:

c++

enums

I am trying to use a class that has an enum type declared inside the class like so:

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; 
};

I need to declare an instance of this class and initialize the enum type. I come from C# and normally see enums declared OUTSIDE of a class, not INSIDE like it is here. How do I initialize the enum type. For example, I want to do something like this:

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

Obviously this doesn't work. How would I do this?

like image 716
Blade3 Avatar asked May 06 '11 15:05

Blade3


2 Answers

First you need to declare a variable that is of the type XEnumType within your class Then you can access the actual enumeration values using the class name for scope: x::LINEAR or x::DIPARABOLIC

class x{
 //Your other stuff

XEnumType myEnum;
};

int main(void)
{
    x myNewClass();
    x.myEnum = x::LINEAR;
}
like image 68
Dan F Avatar answered Nov 15 '22 06:11

Dan F


First: Don't use typedef. Instead, put the name of the enumeration in its head

enum XEnumType {
    LINEAR = 0,      /// Perform linear interpolation on the table
    DIPARABOLIC = 1  /// Perform parabolic interpolation on the table
};

In a nutshell, doing like you did will behave mostly the same, but in arcane corner cases will be different. The syntax you used will behave very different from the syntax I used above only in C.

Second: That just defines a type. But you want to define an object of that enumeration. Do so:

XEnumType e;

In summary:

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;
}
like image 20
Johannes Schaub - litb Avatar answered Nov 15 '22 08:11

Johannes Schaub - litb