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?
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With