C++中enum的使用的一个简单示例

来源:互联网 发布:中国历史 数据库 编辑:程序博客网 时间:2024/05/16 01:59

     在C++中,switch()语句用得很多,但是,switch的参数比较单一,一般只支持Int型,当switch 的参数是复杂的数据类型,如string或自定义的数据类型时,就需要enum对数据类型进行替代。

    如下面这个程序:

#include <iostream.h>
#include <cstdlib>

class Image
{
      public:
             Image( ){ };
             ~Image(){};
             
    enum ImageState
    {
        INIT      = 0, /** < Initialization state */
        READY     = 1, /** < Image ready to use */
        USED      = 2, /** < Image in use */
        DISABLED  = 3, /** < Image can not be instantiated by a VM */
        LOCKED    = 4, /** < FS operation for the Image in process */
        ERROR     = 5  /** < Error state the operation FAILED*/
    };
    
    void set_state(ImageState _state)
    {
         state = _state;
         return ;
     }
     
    ImageState get_state( )
    {
         return state;
    }
    
    int get_size()
    {
        return sizeof(ImageState);
    }
    private:
             ImageState  state;
};
      
      int main()
      {
          Image *aa = new Image();
          aa->set_state(Image::ERROR);
          int c = aa->get_state();
          cout <<"int is "<<sizeof(int)<<endl;
          cout << "ImageState is " <<aa->get_size()<<endl;
          
          cout << "aa is " << c<<endl;
          cout << "aa state is "<<aa->get_state()<<endl;
          
          system("pause");
          return 0;
          
      }

      程序中,定义的Image的状态变量state是一个string类型的值,但是,在作为switch的变量使用时是不可行的,就用enum把state对应的几个string类型值替换成对应的整形值。然后,在使用的时候就是取的整形数值。上述程序的运行结果为:

int is 4

ImageState is 4

aa is 5

aa state is 5

请按任意键继续...


注意,  上述语句aa->set_state(Image::ERROR);中,函数的输入参数ERROR的作用域必须是写包含它的定义的类Image,而不是enum结构的名ImageState。



原创粉丝点击