声明一个车基类,有run stop等成员函数,由此派生bicycle类,motorcar类,bicycle和motorcar派生出摩托车motorcycle类,它们都有run,stop等成员函数
时间: 2024-05-13 09:16:47 浏览: 113
以下是一个基于C++的实现:
```cpp
class Car {
public:
virtual void run() {
cout << "Car is running." << endl;
}
virtual void stop() {
cout << "Car is stopping." << endl;
}
};
class Bicycle : public Car {
public:
void run() {
cout << "Bicycle is running." << endl;
}
void stop() {
cout << "Bicycle is stopping." << endl;
}
};
class Motorcar : public Car {
public:
void run() {
cout << "Motorcar is running." << endl;
}
void stop() {
cout << "Motorcar is stopping." << endl;
}
};
class Motorcycle : public Bicycle, public Motorcar {
public:
void run() {
cout << "Motorcycle is running." << endl;
}
void stop() {
cout << "Motorcycle is stopping." << endl;
}
};
```
在这个实现中,Car是车的基类,拥有run和stop成员函数,Bicycle和Motorcar都是Car的派生类,它们分别实现了run和stop函数。Motorcycle则同时继承了Bicycle和Motorcar,因此它们的成员函数都会被继承下来,在需要时可以重载这些函数以实现特定的行为。
阅读全文