我試圖使用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()
構造固定。
我在想,如果這是最合適的修補程序,或如果有一個解決方案,不涉及一個空的構造。
好的,下一個問題。 比方說,我在那裏有一個setter:無效setPlanet(const的星球與地球){這個 - >行星地球=; } 我不能在那裏使用初始化程序語法。我該如何處理? –
@JamesOltmans如果你需要分配的值存在,不幸的是,你將需要'planet'的指針。 Java中的所有變量都是「指針」,但在C++中,您需要將其明確化。不過,您可以隱藏成員函數接受和返回引用的指針。 – dasblinkenlight