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

2019-09-22 08:50发布

问题:

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

回答1:

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


回答2:

  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:

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


回答4:

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.



标签: c++ class enums