0

我有一个多级继承(来自 Ship 类 -> MedicShip 类 -> Medic 类),其虚函数代码如下。我想结果应该是:

医生 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;
}
4

2 回答 2

1

您还没有创建任何 class 实例Medic。你的意思是说

Medic newMedic;

代替

MedicShip newMedic;

也许?所以,Medic构造函数没有被调用,weighttypeName没有被初始化。

于 2012-04-28T07:59:45.330 回答
0
~Ship(){};

第一个错误就在这里。virtual如果您想通过基类指针删除派生类对象,则应该使用此析构函数 。

于 2012-04-28T07:51:35.887 回答