Frage

I'm trying to access enums from a header file in c++ and getting errors, I think I may just be approaching this in the wrong way.

When I compile the program I get errors saying my enums weren't declared in this scope.

e.g. "error: BASIC was not declared in this scope" "error: ‘PIPE’ was not declared in this scope"

tokenizer.h

typedef struct {
  char *start;
  enum { BASIC, SINGLE_QUOTE, DOUBLE_QUOTE, PIPE, SEMICOLON, EOL, ERROR } type;
} aToken;

simpleshell.cpp

void processLine(char *line)
{
    enum { CMD, PIPED_CMD, ARGS } processMode;
    processMode = CMD;
    Statement *stmt = newStatement();   // Store the current statement
    Command *cmd = NULL;
    int doneFlag = 0;
    char *expandedToken = NULL;

    startToken(line);
    aToken answer;
    answer = getNextToken();

    while (!doneFlag)
    {
        switch (answer.type)
        {
        case ERROR:
            ...  // some code
            return;

        ...  // other case statements

        case PIPE:
            ... // some code
            break;

        case EOL:
            doneFlag = 1;
        default:
            fprintf(stderr, "Programming Error: Unrecognized type returned!!!\n");
            if (cmd != NULL )
            {
                freeCommand(cmd);
                cmd = NULL;
            }
            if (stmt != NULL)
            {
                freeStatement(stmt);
                stmt = NULL;
            }
            return;
        }
        answer = getNextToken();
    }
}
War es hilfreich?

Lösung

You should write it as aToken::BASIC, aToken::PIPE, etc. The enum is enclosed in the scope of aToken.

Andere Tipps

e.g. "error: BASIC was not declared in this scope" "error: ‘PIPE’ was not declared in this scope"

You forgot to apply the struct scope (aToken). You would need to use the enumeration like this:

aToken::myEnumValue

So, you would be writing your code like this:

  switch (answer.type)
    {
    case aToken::ERROR:
    //   ^^^^^^^^
        ...  // some code
        return;

    ...  // other case statements

    case aToken::PIPE:
    //   ^^^^^^^^
        ... // some code
        break;

    case aToken::EOL:
    //   ^^^^^^^^
        doneFlag = 1;
    default:
        fprintf(stderr, "Programming Error: Unrecognized type returned!!!\n");
        if (cmd != NULL )
        {
            freeCommand(cmd);
            cmd = NULL;
        }
        if (stmt != NULL)
        {
            freeStatement(stmt);
            stmt = NULL;
        }
        return;
    }

That being said, you should consider enum classes if you have C++11 support. In that case, you will also need to add the enum class scope as follows:

aToken::MyEnumClass::myEnumValue
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top