【问题标题】:C++ Enumerations: Assign a variable or use scope resolution?C++ 枚举:分配变量还是使用范围解析?
【发布时间】:2014-04-20 13:10:11
【问题描述】:

我正在使用 Visual Studio 2012 编译此 C++ 代码。我注意到我可以在没有范围解析运算符 (::) 的情况下使用枚举值。

这是我的代码在 int main() 之外的重要部分:

enum SortMethod
{
    BY_NAME,
    BY_WEIGHT
};

然后在 int main() 内部我使用以下内容:

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;
}

为什么这些函数调用有效? print() 函数接受一个 SortMethod 参数。所以我想我需要做以下事情:

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

但事实证明,我可以简单地在参数列表中使用“BY_NAME”。这是特定于编译器的吗?

【问题讨论】:

    标签: c++ compiler-construction enums scope-resolution


    【解决方案1】:

    这是因为它是unscoped enumerator,因此每个枚举器都可以在与 enum 名称本身相同的范围内使用。作用域枚举器需要使用::。这在C++ draft standard 部分7.2 枚举声明 段落10 中进行了介绍,其中说:

    每个 enum-name 和每个 unscoped enumerator 都在直接包含 enum-specifier 的范围内声明。每个作用域枚举器都在枚举范围内声明。这些名称遵守 (3.3) 和 (3.4) 中为所有名称定义的范围规则。

    并提供以下示例,direction 的第一个示例使用 无范围的枚举器,并且不需要使用::,但altitude 的第二个示例是范围 因此需要使用:::

    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
    }
    

    【讨论】:

      【解决方案2】:

      C++ 枚举器总是在包含枚举的范围内声明。 C++11 添加了使用 enum class 而不是 enum 关键字定义的“作用域枚举器”。

      【讨论】:

        【解决方案3】:

        不。 enums 只是 ints。默认情况下,值从零开始编号,因此您的枚举隐式声明为:

        enum SortMethod
        {
            BY_NAME = 0,
            BY_WEIGHT = 1
        }
        

        因此,这些值可以在任何可以使用整数的地方使用。

        如果使用作用域枚举器,它会变得更加复杂。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-24
          • 2012-08-12
          • 1970-01-01
          • 2014-09-20
          • 2012-08-07
          • 1970-01-01
          • 2013-06-01
          • 1970-01-01
          相关资源
          最近更新 更多