Home > OS >  How to use enum in class (C )?
How to use enum in class (C )?

Time:11-16

enum  TokenType{
    Eof,
    Ws,

    Unknow,

    //lookahead 1 char
    If,Else,
    Id,
    Int,

    //lookahead 2 chars
    Eq,Ne,Lt,Le,Gt,Ge,

    //lookahead k chars
    Real,
    Sci
};
class Token{
private:
    TokenType token;
    string text;
public:
    Token(TokenType token,string text):token(token),text(text){};
    static Token eof(Eof,"Eof");
};

In this code I want to create a Token Object eof, but when I compile it it tells me that the Eof is not a Type. Why?

When I use TokenType token=TokenType::Eof it works. But when I passed the Eof into the constructor as a parameter, an error occurred. How could I solve it? Is it related to the scope. I try to use TokenType::Eof as the parameter also fail.

CodePudding user response:

The problem is unrelated to the enumeration, the problem is that the compiler thinks you're declaring a function. For inline initialization use either curly braces {} or assignment-like syntax.

However, you can't define instances of a class inside the class itself, because the class isn't actually fully defined yet. It will also leas to a kind of infinite recursion (Token contains a Token object, which contains a Token object, which contains a Token object, ... and so on in infinity).

You can, on the other hand, define pointers to class inside itself, or references, because that doesn't require a fully defined class, only knowledge that the class exists.

So as a workaround perhaps use reference, that you initialize to a variable defined outside the class:

class Token
{
    // ...

private:
    static Token& eof;  // Declare the reference variable
};

And in a source file:

namespace
{
    // Define the actual "real" instance of the eof object
    Token eof{ Eof, "Eof" };
}

// Define the reference and initialize it
Token& Token::eof = eof;

CodePudding user response:

Look closely. The error messages tells you where exactly your error lies, including a line number. The compiler sees a function prototype, with Eof being the type of the first argument.

Because Eof is not a type, but just one possible value of a type.

It's really not clear what your design intent here is, but you need to make a clear mental difference between the type you've created, TokenType and its different values.

  • Related