多级继承/多态性和虚函数
Multilevel inheritance/polymorphism and virtual function
我有一个多级继承(来自船类->医疗船类->医疗类),虚函数代码如下。我想结果应该是:
医生 10
医生 10
但它产生了奇怪的结果。另一方面,如果我只使用一个级别的继承(来自 Ship 类 -> Medic 类,中间没有 MedicShip 类),结果就可以了。 你能找到我的错误吗?非常感谢...
#ifndef FLEET_H
#define FLEET_H
#include <string>
#include <vector>
using namespace std;
class Ship
{
public:
Ship(){};
~Ship(){};
int weight;
string typeName;
int getWeight() const;
virtual string getTypeName() const = 0;
};
class MedicShip: public Ship
{
public:
MedicShip(){};
~MedicShip(){};
string getTypeName() const;
};
class Medic: public MedicShip
{
public:
Medic();
};
class Fleet
{
public:
Fleet(){};
vector<Ship*> ships;
vector<Ship*> shipList() const;
};
#endif // FLEET_H
#include "Fleet.h"
#include <iostream>
using namespace std;
vector<Ship*> Fleet::shipList() const
{
return ships;
}
int Ship::getWeight() const
{
return weight;
}
string Ship::getTypeName() const
{
return typeName;
}
string MedicShip::getTypeName() const
{
return typeName;
}
Medic::Medic()
{
weight = 10;
typeName = "Medic";
}
int main()
{
Fleet fleet;
MedicShip newMedic;
fleet.ships.push_back(&newMedic);
fleet.ships.push_back(&newMedic);
for (int j=0; j< fleet.shipList().size(); ++j)
{
Ship* s = fleet.shipList().at(j);
cout << s->getTypeName() << "t" << s->getWeight() << endl;
}
cin.get();
return 0;
}
您尚未创建类Medic
的任何实例。你的意思是说
Medic newMedic;
而不是
MedicShip newMedic;
也许?因此,不会调用 Medic
构造函数,也不会初始化weight
和typeName
。
~Ship(){};
第一个错误就在这里。如果要通过基类指针删除派生类对象,则应virtual
此析构函数。
相关文章:
- 从基类调用函数的多态性
- C++多态性:有没有办法找到对象成员函数的地址?
- C++ 多态性:如果派生类中的虚函数在基类中声明了常量,是否需要将其声明为常量
- 如果基类指针无法访问派生类成员函数,那么多态性有什么方便的呢?
- 多态性在 lambda 函数C++不起作用
- 多态性是否适用于值?或者在按(基)值返回时使用派生类的移动构造函数
- 如何在保持多态性的同时,将成员函数添加到需要它的继承类中,而不会影响其他同级类?
- C++ 中多态性和函数重载之间的区别
- 函数模板和多态性
- C 多态性实例的构造函数和破坏者
- 多态性(C )的派生类中的超载函数
- 多态性和纯虚函数
- C++ 多态性和非虚函数
- C++多态性/虚拟函数在此不起作用
- 如果重载函数仅被部分重写,则多态性不起作用
- 多态性不适用于相同数据类型(Base和Inherited类)的函数返回值
- 具有引用数据类型的函数多态性
- c++在没有虚拟析构函数的多态性中共享ptr
- 模板函数多态性
- 基类和派生类构造函数多态性问题