2012-04-28 59 views
0

我有一个多级继承(从船舶类 - > MedicShip类 - >苜蓿类)与如下虚拟功能码。我想结果应该是:多级继承/多态性与虚拟功能

梅迪奇10
梅迪奇10

但它产生的奇怪结果。另一方面,如果我只使用一级继承(来自Ship类 - >无MedicShip类的Medic类),那么结果就可以。你能找到我的错误吗?许多感谢....

#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; 
} 
+2

结果是什么? – hmjd 2012-04-28 07:51:13

+0

也许结果太奇怪了,无法在这里透露。 – 2012-04-28 08:16:51

回答

0
~Ship(){}; 

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

+0

真的够了,很重要,但是* damar *报告的问题是无关紧要的。 (碰巧在这种情况下,错误没有任何不良后果,因为派生类不需要和破坏时不需要做任何与基类不同的任何操作。) – 2012-04-28 08:05:13

+0

是的你是对的。我错过了。非常感谢纳瓦兹。第二个答案Gareth McCaughan也发现我的错误。它应该是Medic medicalMedic而不是MedicShip newMedic。现在起作用了。 – damar 2012-04-28 08:11:29

1

您尚未创建Medic类的任何实例。你的意思是说的

Medic newMedic; 

代替

MedicShip newMedic; 

吧?因此,Medic构造函数未被调用,并且weighttypeName未被初始化。

+0

是的,你是对的Gareth。我的错只是从我以前的代码中复制出来的。非常感谢。它现在工作... – damar 2012-04-28 08:13:35