C++ How can I access to an inner enum class?

2019-09-22 08:40发布

I am facing a problem in 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;

}

When I try to compile this code following message appears:

[Error] 'Apple::color' is not a class or namespace

标签: c++ class enums
4条回答
我只想做你的唯一
2楼-- · 2019-09-22 08:47
  1. Looks like you're using a pre C++11 compiler or c++11 flag is not enabled.
  2. After using correct c++11 flag, you will have to overload operator <<

    friend std::ostream& operator <<( std::ostream& os, const color& c )
    {
      /* ... */
      return os;
    }
    
查看更多
混吃等死
3楼-- · 2019-09-22 08:52

P0W's answer is correct on both counts, but in case you simply want to output the underlying value, then it may be simpler to cast rather than overload the insertion operator.

using enum_type = std::underlying_type<Apple::color>::type;
enum_type value = (enum_type)Apple::color::green;
std::cout << value << '\n';
查看更多
Melony?
4楼-- · 2019-09-22 08:54

In order to use enum class your compiler has to support C++11. This can be for example achieved by appending a -std=c++11 after your clang or g++ build command if you are using those. New versions of Visual Studio enable C++11 automatically.

The error that you should be getting is no operator "<<, as pointed out by @pvl, since enum class doesn't convert to anything implicitly and therefore won't output an integer value.

查看更多
姐就是有狂的资本
5楼-- · 2019-09-22 09:00
  • Enable c++11 cause enum class are a c++11 feature suing the --std=c++11 compiler flag.

  • Overload the << operator if you want to cout an Apple::color

Something like the following should work:

#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;
}
查看更多
登录 后发表回答