声明一个vehicle基类,有run stop等成员函数,由此派生bicycle类,motorcar类,bicycle和motorcar派生出摩托车motorcycle类,它们都有run,stop等成员函数 点击复制后,将打开C知道体验页
时间: 2024-05-04 21:20:52 浏览: 102
很好,以下是基于C++的代码实现:
```
class Vehicle {
public:
virtual void run() {
cout<<"Vehicle is running"<<endl;
}
virtual void stop() {
cout<<"Vehicle has stopped"<<endl;
}
};
class Bicycle : public Vehicle {
public:
void run() {
cout<<"Bicycle is running"<<endl;
}
void stop() {
cout<<"Bicycle has stopped"<<endl;
}
};
class Motorcar : public Vehicle {
public:
void run() {
cout<<"Motorcar is running"<<endl;
}
void stop() {
cout<<"Motorcar has stopped"<<endl;
}
};
class Motorcycle : public Bicycle, public Motorcar {
public:
void run() {
cout<<"Motorcycle is running"<<endl;
}
void stop() {
cout<<"Motorcycle has stopped"<<endl;
}
};
```
在代码中,我们定义了一个基类Vehicle,它包含了run()和stop()两个成员函数。接着,我们分别定义了Bicycle和Motorcar两个派生类,并且重写了它们的run()和stop()函数。最后,我们定义了一个Motorcycle类,它是由Bicycle和Motorcar派生而来,同时也重写了run()和stop()函数。
需要注意的是,Motorcycle类继承了Bicycle和Motorcar类,这里使用了多重继承。因此,在Motorcycle类中,我们需要重写run()和stop()函数,以避免出现冲突。
阅读全文