【问题标题】:C++ How can I access to an inner enum class?C++ 如何访问内部枚举类?
【发布时间】:2018-01-22 04:26:28
【问题描述】:

我在 C++ 中遇到了一个问题:

#include <iostream>
 class Apple{
public:
    int price = 100;
    enum class color {
    red =1, green, yellow
    };



};
int main() {
 Apple apple;
 std::cout << Apple::color::green << std::endl;

}

当我尝试编译此代码时,会出现以下消息:

[错误] 'Apple::color' 不是类或命名空间

【问题讨论】:

  • 您使用的是哪个版本的 C++?从 c++11 开始支持枚举类。当我运行您的示例时,它给了我一个“没有运算符“
  • 这不是问题,但您真的需要std::endl 需要的额外内容吗? ``\n'` 结束一行。

标签: c++ class enums


【解决方案1】:
  1. 看起来您正在使用预 C++11 编译器或未启用 C++11 标志。
  2. 使用正确的 c++11 标志后,您将不得不重载 operator &lt;&lt;

    friend std::ostream& operator <<( std::ostream& os, const color& c )
    {
      /* ... */
      return os;
    }
    

【讨论】:

    【解决方案2】:
    • 启用c++11,因为enum class 是使用--std=c++11 编译器标志的c++11 功能。

    • 如果你想要coutApple::color,请重载&lt;&lt; 运算符

    类似下面的东西应该可以工作:

    #include <iostream>
    
    class Apple {
     public:
      int price = 100;
      enum class color { red = 1, green, yellow };
    };
    
    std::ostream& operator<<(std::ostream& os, const Apple::color& c) {
      if (c == Apple::color::red) std::cout << "Red\n";
      if (c == Apple::color::green) std::cout << "Green\n";
      if (c == Apple::color::yellow) std::cout << "Yellow\n";
      return os;
    }
    
    int main() {
      Apple apple;
      std::cout << Apple::color::green << std::endl;
    }
    

    【讨论】:

      【解决方案3】:

      为了使用enum class,您的编译器必须支持 C++11。例如,这可以通过在您的 clang 或 g++ 构建命令(如果您正在使用这些命令)之后附加 -std=c++11 来实现。新版本的 Visual Studio 自动启用 C++11。

      正如@pvl 指出的那样,您应该得到的错误是no operator "&lt;&lt;,因为enum class 不会隐式转换为任何内容,因此不会输出整数值。

      【讨论】:

      • 强制转换总是显式的——它是您在源代码中编写的内容,告诉编译器进行转换。问题是没有隐式转换
      【解决方案4】:

      P0W 的答案在这两个方面都是正确的,但如果您只想输出基础值,那么强制转换可能比重载插入运算符更简单。

      using enum_type = std::underlying_type<Apple::color>::type;
      enum_type value = (enum_type)Apple::color::green;
      std::cout << value << '\n';
      

      【讨论】:

      • 您至少可以在示例中使用 static_cast 而不是 C 风格的演员表
      • @kim366 我可以,但我也不必这样做。我发现 C 风格的转换更容易阅读,并且考虑到上下文,没有机会误解转换的类型。
      猜你喜欢
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2012-01-17
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多