How to use a Java-like C ++ variable as a member variable of another class?

I am trying to use a solution for java-like enumerations in C ++ .

My problem is that I am trying to use enum as a member in another class. So, first we start with the familiar enumeration of the 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

Then we have an object SolarSystemthat accepts objects 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

Now, if we try to compile this, we get the following errors:

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

The problem can be fixed by including an empty constructor Planet().

I was wondering if this is the most appropriate fix or if there is a solution that does not include an empty constructor.

+3
source share
2 answers

Planet planet . ++ Planet - , .

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

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

};
+3

++ 11, Java- ++ (fooobar.com/questions/118212/...), 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;
};
+1

All Articles