enum 用一个类或结构体来限定其作用域,例如:定义新变量的方法和上面命名空间的相同。不过这样就不用担心类在别处被修改内容。这里用结构体而非类,一是因为本身希望这些常量可以公开访问,二是因为它只包含数据没有成员函数。
#include <iostream>
using namespace std;
namespace Color
{
enum Type
{
RED=15,
YELLOW,
BLUE
};
};
struct Color1
{
enum Type
{
RED=102,
YELLOW,
BLUE
};
};
enum class Color2
{
RED=2,
YELLOW,
BLUE
};
enum class Color3:char;
enum class Color3:char
{
RED='r',
BLUE
};
int main()
{
Color::Type c = Color::RED;
cout<<"c="<<c<<endl;
Color1 c1;
cout<<c1.RED<<endl;
Color1::Type c11 = Color1::BLUE;
cout<<c11<<endl;
Color2 c2 = Color2::RED;
cout << static_cast<int>(c2) << endl;
char c4 = static_cast<char>(Color3::RED);
cout<<c4<<endl;
char c3 = static_cast<char>(Color3::BLUE);
cout<<c3<<endl;
return 0;
}