Home > database >  What type do I use in the constructor to initialize a member variable defined by a nameless enum?
What type do I use in the constructor to initialize a member variable defined by a nameless enum?

Time:10-03

I have a struct containing a member variable category which I guess is of type "nameless enum".

struct Token {
    Token();
    enum {
            NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS
    } category;
    union { 
        char variable;
        double number;
    };
};

As you can see I also have a constructor Token(). I would like to be able to use the constructor like this:

Token my_token(Token::NUMBER, 5);

Instead of doing something like this:

Token my_token;
my_token.category = Token::NUMBER;
my_token.number = 5;

My question now is, what types do I use for the constructor? I tried something like this:

//declaration
Token(int category, int number);

//definition
Token(int category, int number) : category(category), number(number) {}

But then when I try to initialize an object of the Token struct I get:
error: invalid conversion from ‘int’ to ‘Token::<unnamed enum>’ [-fpermissive]

I would like to keep the enum inside of the struct, some help with what type to use to initialize the union would also be appreciated.

CodePudding user response:

Something like this?

struct Token {
    enum EN {
            NUMBER, VARIABLE, PLUS, MINUS, PRODUCT, DIVISION, POWER, SIN, COS
    } category;
    union { 
        char variable;
        double number;
    };
    Token(const EN c, const double n) noexcept : category(c), number(n) {}
    //... Other constructors...
};

int main()
{
    Token t(Token::NUMBER, 3.4);
}

But I'd assign the category internally

  • Related