虚函数可以实现多态性摩托车类,即不同的对象调用同一个函数,可以有不同的行为。在此基础上,我们可以重写(override)基类的虚函数,使得派生类可以按照自己的需求来实现该函数输出把基类中Run、Stop声明为虚函数时主程序的输出结果
时间: 2024-03-16 17:45:56 浏览: 12
当把基类中的 `Run` 和 `Stop` 函数声明为虚函数时,派生类可以重写(override)这两个函数,因此不同类型的对象调用 `Run` 和 `Stop` 时,会根据对象的类型决定调用哪个重写函数,实现多态性。具体实现如下所示:
```python
class Vehicle:
def Run(self):
print("Vehicle is running")
def Stop(self):
print("Vehicle has stopped")
class Bicycle(Vehicle):
def Run(self):
print("Bicycle is running")
def Stop(self):
print("Bicycle has stopped")
class Motorcar(Vehicle):
def Run(self):
print("Motorcar is running")
def Stop(self):
print("Motorcar has stopped")
class Motorcycle(Bicycle, Motorcar):
def Run(self):
print("Motorcycle is running")
def Stop(self):
print("Motorcycle has stopped")
v = Vehicle()
v.Run()
v.Stop()
b = Bicycle()
b.Run()
b.Stop()
m = Motorcar()
m.Run()
m.Stop()
mc = Motorcycle()
mc.Run()
mc.Stop()
```
这里对基类 `Vehicle` 中的 `Run` 和 `Stop` 函数进行了虚函数声明,派生类 `Bicycle`、`Motorcar` 和 `Motorcycle` 分别重写了这两个函数。当不同类型的对象调用 `Run` 或 `Stop` 函数时,会根据对象的类型决定调用哪个重写函数,实现多态性。
输出结果为:
```
Vehicle is running
Vehicle has stopped
Bicycle is running
Bicycle has stopped
Motorcar is running
Motorcar has stopped
Motorcycle is running
Motorcycle has stopped
```
可以看到,不同类型的对象调用 `Run` 或 `Stop` 函数时,表现出了不同的行为,实现了多态性。