基于公共参数 c++ 调用某些类的构造函数
Calling constructors of certain classes based upon a common parameter c++
我目前正在研究类中的类继承/多态性,但我无法弄清楚这个问题。好的,这里是:假设我有 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
}
}
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 减少复制构造函数调用
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在 Google 测试中,我可以从构造函数调用 GetParam() 吗?
- C++ - 从另一个类构造函数调用类构造函数
- 在C++中初始化带有和不使用构造函数调用的对象有什么区别
- 是否可以从移动构造函数调用默认构造函数?
- 在模板生成器模式中分解重复的构造函数调用
- std::atexit 从全局对象的构造函数调用时的排序
- 对构造函数调用的约束
- 编译器错过了无效的构造函数调用,并调用不存在的(或私有的)默认构造函数
- 用构造函数调用填充向量
- 创建指针时是否没有构造函数调用
- 使用 emplace_back 避免移动构造函数调用的最佳方法?
- C++ 抽象类构造函数调用
- 为什么函数参数将带有参数的构造函数调用
- 为什么比“构造函数”调用更多的“解构器”调用
- 将对象传递给函数并不是导致构造函数调用