enum 随笔

工作中的代码常看到在一个类里面定义一个 enum , 而只用这个 enum,  也许没有把它放到类中的必要, 但是不放到类中, 每一个枚举量在namespace就是直接可见的, 也不太好

写了个测试小程序

注意到,  enum和int是一个size,  4 bytes.   enum中的枚举量(常量), 在它所在的namespace中直接可见,   class也是定义了一个namespace

20,21行两种转换方式, 不转换是编译不过的

22,23 两种定义枚举变量的方式

 

  1 #include <iostream>
2 using namespace std;
3
4 enum Type {
5 A = 0,
6 B ,
7 C = 6
8 };
9
10 class WY {
11 public: // private by default
12 enum Love {
13 SOCCER,
14 GIRL = 5,
15 CODING = 9
16 };
17 }; // ; needed after class definition
18
19 int main (){
20 cout<<"the size of enum Type:" << sizeof(Type) << endl
21 <<"the size of int:" << sizeof(int) << endl;
22 Type type = static_cast<Type>(5);
23 enum Type type2 = Type(7); //两种定义方式, 下面这种好
24 // cout << "Type::A = " << Type::A <<endl; //error, Type is not a class or a namespace
25 cout << "A = " << A << endl;
26 cout << "B = " << B << endl;
27 cout << "C = " << C << endl;
28 cout << "type = " << type << endl;
29 cout << "type2 = " << type2 << endl;
30 // A++; //error
31 // type++; //error
32
33 int t = C * 2;
34 cout << "t = " << t << endl;
35
36 t = WY::GIRL;
37 cout << "again t = " << t <<endl;
38 return 0;
39 }

编译结果

the size of enum Type:4
the size of int:4
A = 0
B = 1
C = 6
type = 5
type2 = 7
t = 12
again t = 5

 



posted on 2012-02-16 21:07  小宇2  阅读(327)  评论(0编辑  收藏  举报

导航