3

私はC++でJavaのような列挙型のソリューションを使用しようとしています。

私の問題は、列挙型を別のクラスのメンバーとして使用しようとしていることです。したがって、最初に、おなじみのPlanet列挙型から始めます。

#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()コンストラクターを含めることで修正できます。

それが最も適切な修正なのか、それとも空のコンストラクターを含まない解決策があるのか​​疑問に思いました。

4

2 に答える 2

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;

};
于 2012-05-23T23:06:19.840 に答える
1

c ++ 11を使用する場合は、私が説明したJavaのようなC ++列挙型メソッド(https://stackoverflow.com/a/29594977/558366)を使用することもできます。これは、基本的にint変数のラッパークラスであり、 Planetは、通常の列挙型とほぼ同じように使用できます(キャストとの間のキャストをサポートし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;
};
于 2015-04-12T22:03:51.973 に答える