2012-05-23 26 views
3

我試圖使用solution for java-like enums in C++如何使用類Java的C++枚舉作爲另一個類的成員變量?

我的問題是,我試圖使用枚舉作爲另一個類中的成員。 所以首先我們先從熟悉的星球枚舉:

#ifndef PLANETS_H 
#define PLANETS_H 

class Planet { 
    public: 
    static const double G = 6.67300E-11; 
    // 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: 

    double surfaceGravity() { 
     return G * mass/(radius * radius); 
    } 
}; 

// 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); 

#endif // PLANETS_H 

然後我們有一個SolarSystem對象,需要Planet對象。

#ifndef SOLARSYSTEM_H 
#define SOLARSYSTEM_H 

#include "Planets.h" 
class SolarSystem { 
    public: 
    SolarSystem(int distance, const Planet& planet) { 
     this->distance = distance; 
     this->planet = planet; 
    } 

    private: 
    int distance; // in kilometers 
    Planet planet; 

}; 


#endif // SOLARSYSTEM_H 

現在,如果我們試圖編譯這個我們獲得了以下錯誤:

SolarSystem.h: In constructor 'SolarSystem::SolarSystem(int, const Planet&)': 
SolarSystem.h:7:53: error: no matching function for call to 'Planet::Planet()' 
SolarSystem.h:7:53: note: candidates are: 
Planets.h:17:5: note: Planet::Planet(double, double) 
Planets.h:17:5: note: candidate expects 2 arguments, 0 provided 
Planets.h:4:7: note: Planet::Planet(const Planet&) 
Planets.h:4:7: note: candidate expects 1 argument, 0 provided 

的問題可以通過包括空Planet()構造固定。

我在想,如果這是最合適的修補程序,或如果有一個解決方案,不涉及一個空的構造。

回答

3

你應該Planet planet的引用,在初始化列表中初始化。否則,C++會嘗試複製一個Planet的實例 - 正是您想要避免的事情。

class SolarSystem { 
public: 
    SolarSystem(int distance, const Planet& planet) 
    : distance(distance) 
    , planet(planet) { 
    } 

private: 
    int distance; // in kilometers 
    const Planet& planet; 

}; 
+0

好的,下一個問題。 比方說,我在那裏有一個setter:無效setPlanet(const的星球與地球){這個 - >行星地球=; } 我不能在那裏使用初始化程序語法。我該如何處理? –

+0

@JamesOltmans如果你需要分配的值存在,不幸的是,你將需要'planet'的指針。 Java中的所有變量都是「指針」,但在C++中,您需要將其明確化。不過,您可以隱藏成員函數接受和返回引用的指針。 – dasblinkenlight

1

如果使用C++ 11,也可以使用予描述的類似Java的C++枚舉法(https://stackoverflow.com/a/29594977/558366),它基本上是圍繞一個int變量一個包裝類並允許幾乎使用行星就好像它是一個普通的枚舉類型(它支持鑄造,並從int並具有大小相同int),但仍具有構件的功能,如planet.SurfaceGravity()。這將允許您的太陽能系統標題進行編譯(儘管您可以並應該刪除構造函數中Planet參數的引用):

class SolarSystem { 
    public: 
    SolarSystem(int distance, Planet planet) { 
     this->distance = distance; 
     this->planet = planet; 
    } 

    private: 
    int distance; // in kilometers 
    Planet planet; 
}; 
相關問題