質問

I'm compiling this C++ code with Visual Studio 2012. I noticed that I could use enumeration values without a scope resolution operator (::).

Here's the important parts of my code outside of int main():

enum SortMethod
{
    BY_NAME,
    BY_WEIGHT
};

Then inside of int main() I use the following:

int main()
{
    LinkedList* list = new LinkedList();
    /*
        Insert values into linked list, in sorted order.
    */
    list->print( BY_NAME );
    cout << endl << endl;
    list->print( BY_WEIGHT );

    return 0;
}

Why do these function calls work? The print() function accepts one SortMethod argument. So I figured I would need to do the following:

SortMethod sortByName = BY_NAME;
list->print( sortByName );

But it turns out that I can simply use 'BY_NAME' in the parameter list. Is this compiler-specific?

役に立ちましたか?

解決

That is because it is unscoped enumerator and so each enumerator is available in the same scope as the enum name itself. A scoped enumerator would require to use of ::. This is covered in the C++ draft standard section 7.2 Enumeration declarations paragraph 10 which says:

Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier. Each scoped enumerator is declared in the scope of the enumeration. These names obey the scope rules defined for all names in (3.3) and (3.4).

and provides the following example, the first example with direction uses an unscoped enumerator and does not require the use of :: but the second example with altitude is scoped and thus requires the use of :::

enum direction { left=’l’, right=’r’ };

void g() {
  direction d; // OK
  d = left; // OK
  d = direction::right; // OK
}

enum class altitude { high=’h’, low=’l’ };

void h() {
  altitude a; // OK
  a = high; // error: high not in scope
  a = altitude::low; // OK
}

他のヒント

C++ enumerators are always declared in the scope that contains the enum. C++11 added "scoped enumerators" defined by using enum class instead of enum keyword.

Nope. enums are merely ints. By default, the values are numbered from zero forward, so your enum is implicitly declared as:

enum SortMethod
{
    BY_NAME = 0,
    BY_WEIGHT = 1
}

So, the values can be used anywhere an integer can be used.

It gets more complicated if you use scoped enumerators.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top