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