How to write a Java-enum-like class with multiple data fields in C++?

前端 未结 4 683
感情败类
感情败类 2020-11-30 21:32

Coming from a Java background, I find C++\'s enums very lame. I wanted to know how to write Java-like enums (the ones in which the enum values are objects, and can have attr

4条回答
  •  -上瘾入骨i
    2020-11-30 21:55

    One way to simulate Java enums is to create a class with a private constructor that instantiates copies of itself as static variables:

    class Planet {  
      public: 
        // Enum value DECLARATIONS - they are defined later 
        static const Planet MERCURY;  
        static const Planet VENUS;  
        // ... 
    
      private: 
        double mass;   // in kilograms  
        double radius; // in meters  
    
      private: 
        Planet(double mass, double radius) {  
            this->mass = mass;  
            this->radius = radius;  
        } 
    
      public: 
        // Properties and methods go here 
    }; 
    
    // Enum value DEFINITIONS 
    // The initialization occurs in the scope of the class,  
    // so the private Planet constructor can be used. 
    const Planet Planet::MERCURY = Planet(3.303e+23, 2.4397e6);  
    const Planet Planet::VENUS = Planet(4.869e+24, 6.0518e6);  
    // ... 
    

    Then you can use the enums like this:

    double gravityOnMercury = Planet::MERCURY.SurfaceGravity();
    

提交回复
热议问题