基于公共参数 c++ 调用某些类的构造函数

Calling constructors of certain classes based upon a common parameter c++

本文关键字:构造函数 调用 于公共 参数 c++      更新时间:2023-10-16

我目前正在研究类中的类继承/多态性,但我无法弄清楚这个问题。好的,这里是:假设我有 2 个模拟类,我让用户选择一个与构造函数中最后一个参数对应的值:

class Planets {
private:
    int x,y,z;
    string a;
public:
    Planets(string name, int diameter, int mass, int planet_kind) : a(name), x(diameter), y(mass), z(planet_kind) { }
    Planets() { a="", x=0, y=0, z=0; }
    //get and set functions to manipulate data
    virtual void planet_creation(Planets& p1);
    //function I want to modify depending on the planet
}

需要注意的是planet_kind变量。我希望父类是其他类的基线,例如,气态巨行星是 2,有生命的行星是 1,等等......它们都有自己的类和构造函数。例如在另一个类中:

class Gas_giant : public Planets {
private:
    int x,y,z;
    string a;
public:
    Gas_giant(string name, int diameter, int mass, int planet_kind) : a(name), x(diameter), y(mass), z(planet_kind) { }
    Gas_giant() { a="Gas", x=0, y=0, z=2; }
    //get and set functions to manipulate data
    void planet_creation(Gas_giant& g);
    //function I want to modify depending on the planet
    //example: gas giants would be larger when created,have no solid mass,high gravity
}    

基本上,我希望用户能够输入行星的种类和名称,然后根据他们选择的种类,调用某些类型的行星以不同的方式随机生成。函数不是问题,我遇到的问题是让我的程序根据基本构造函数中的参数选择不同的构造函数。

不希望我的程序创建任何"0型"行星,它只是一个我试图从中推导出其余部分的类。

提前感谢,如果这是一个愚蠢的问题,很抱歉。

在某些语言中,构造函数可以返回派生类型,但C++不是其中之一。在C++构造函数总是精确地构造自己的类型。

无论如何,使用"planet_kind"整数优于使用不同的构造函数并不明显。不同的构造函数选项可能更具可读性:

Planet* henry = new GasGiant("Henry", ...);
Planet* bob   = new Asteroid("Bob", ...);
...

如果您出于某种原因确实需要使用枚举(例如从文件中读取数据),那么您需要一个 case 语句:

for (;;) {
  // read data into name, size, mass, kind
  planets.emplace_back( make_planet(name, size, mass, kind) );
}
...
Planet* make_planet(std::string name, double radius, double mass, enum PlanetKind kind) {
  switch (kind) {
    case GIANT   : return new GasGiant(name, radius, mass);
    case ASTEROID: return new Asteroid(name, radius, mass);
    // ...
    default: // write an error message
  }
}