2017-10-08 175 views
-2

我只是修改了OOP的基本概念,我碰到了這個問題。該程序的作品,但我不明白爲什麼它的作品。我有一個基類Vehicle和子類Car和孫子班TwoDoorCar。下面的代碼給出:C++:孫子類沒有實現父類和子類的虛函數,程序工作

class Vehicle { 
private: 
    int wheels; 
    string make; 
protected: 
    int protect; 
public: 
virtual ~Vehicle(){} 
Vehicle(){ 
    cout << "empty Vehicle constructor" << endl; 
    this->wheels = 0; 
    this->make = ""; 
    this->protect = 0; 
} 

Vehicle(int wheel,string m){ 
    cout << "parametrized Vehicle constructor" << endl; 
    this->wheels = wheel; 
    this->make = m; 
    this->protect = 0; 
} 

void ctest() const{ // read only function 
    cout << "ctest() called" << endl; 
} 

virtual void Drive() = 0; 

const string& getMake() const { 
    return make; 
} 

void setMake(const string& make) { 
    this->make = make; 
} 

int getWheels() const { 
    return wheels; 
} 

void setWheels(int wheels) { 
    this->wheels = wheels; 
} 
}; 

class Car : virtual public Vehicle { 
private: 
int carNumber; 
public: 
virtual ~Car(){} 
Car():Vehicle(){ 
    cout << "empty car constructor" << endl; 
    carNumber = 0; 
} 

Car(int wheels, string make, int Number) : Vehicle(wheels,make){ 
    cout << "Car's constructor called" << endl; 
    this->carNumber = Number; 
} 

Car(int wh, string m): Vehicle(wh, m){ 
    this->carNumber = 0; 
} 

virtual void Drive(){ 
    cout << "Car driven " << endl; 
} 

virtual void Drive(string p){ 
    cout << "Over loaded function of Drive with string argument : " << p << endl; 
} 

void testProtect(){ 
    cout << "Car::Protected member " << this->protect << endl; 
} 
}; 

class TwoDoorCar : public Car{ 
public: 
virtual ~TwoDoorCar(){} 
TwoDoorCar():Car(){ 
    cout << "Empty two door car constructor" << endl; 
} 

TwoDoorCar(int wheels, string make, int reg) : Car(wheels,make,reg){ 

} 

}; 

的純虛函數Drive()在子類中定義,但不是在孫類。我在子類中嘗試使用virtual,但該程序在孫子類中沒有功能實現Drive()函數。

我用下面的代碼運行

TwoDoorCar tdc1; 
Vehicle * v3 = &tdc1; 
v3->Drive(); 

程序的輸出是

empty Vehicle constructor 
empty car constructor 
Empty two door car constructor 
Car driven 

任何人都可以解釋爲什麼沒有錯誤在這裏,即使純虛擬和虛擬在基地使用,孩子班分別?

+0

它使用'Car :: Drive'功能。 –

+0

一旦實現了純虛函數,就不再需要在其他派生類中實現。 – user0042

+2

您是否真的需要在我們身上轉儲這麼多代碼來說明這個簡單問題?考慮[mcve]的* minimal *方面。 – StoryTeller

回答

0

只需要定義純虛函數。虛擬函數可以由繼承類派生,並且不需要在繼承類中重新定義。