2012-04-28 60 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