2017-10-08 171 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

只需要定义纯虚函数。虚拟函数可以由继承类派生,并且不需要在继承类中重新定义。