继承中的构造函数

Constructor in inheritance

本文关键字:构造函数 继承      更新时间:2023-10-16

如何在Tanks类上声明构造函数,以便创建新对象,如

tanks t34(durability, velocity, damage);

这是我的课:

#include <iostream>
using namespace std;
class vehicles{
private:
    double durability;
    double velocity;
public:
     void drive() { cout << "driven"; }
     void info() { cout << durability << " " << velocity << "n"; }
     vehicles(double d, double v) : durability(d), velocity(v) {}
     ~vehicles() {}
};
class tanks:public vehicles{
private:
    double damage;
public:
    using vehicles::vehicles;
    tanks(double dmg) : damage(dmg) {}
    void shot();
};

所以我想从复制变量

vehicles(double d, double v) : durability(d), velocity(v) {}

并将其添加到坦克类中。

只需在tanks:中添加另一个构造函数

tanks(double dmg, double v, double d):vechicles(d,v), dmanage(dmg) {}
                                    //^^call base class constructor to init base part

然后您应该能够创建tanks的对象,如下所示:

tanks t34(durability, velocity, damage);