编写程序声明一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车 (motorcar)类。从bicycle和motorcar派生出摩托车(motorcycle)类。他们都有Run、Stop等成员函数。在main( )函数中声明vehicle、bicycle、motorcar、motorcycle的对象,分别调用其Run( )、Stop( )函数,观察其执行情况。再分别用vehicle类型的指针来调用这几个对象的成员函数,看看能否成功;把Run、Stop声明为虚函数,再试试看。观察虚函数的作用。 输入 输出 vehicle is running... vehicle is stopped... bicycle is running... bicycle is stopped... motorcar is running... motorcar is stopped... motorcycle is running... motorcycle is stopped... --------------------------------------- vehicle is running... vehicle is stopped... bicycle is running... bicycle is stopped... motorcar is running... motorcar is stopped... motorcycle is running... motorcycle is stopped... #include <iostream> using namespace std; class vehicle { ...... }; class bicycle...... { ...... }; class motorcar..... { ....... }; class motorcycle....... { ...... }; int main() { vehicle v,*pv; bicycle by; motorcar mc; motorcycle mcy; //此处通过对象名来调用各成员函数 ......... cout<<"---------------------------------------\n"; pv=&v; pv->Run(); pv->Stop(); ........ pv->Run(); pv->Stop(); ....... pv->Run(); pv->Stop(); ....... pv->Run(); pv->Stop(); return 0; }
时间: 2024-02-21 12:00:45 浏览: 131
这是一道基础的面向对象编程题目,需要定义一些类并进行继承。具体的代码实现如下:
```python
#include <iostream>
using namespace std;
class vehicle {
public:
virtual void Run() {
cout << "vehicle is running..." << endl;
}
virtual void Stop() {
cout << "vehicle is stopped..." << endl;
}
};
class bicycle : public vehicle {
public:
virtual void Run() {
cout << "bicycle is running..." << endl;
}
virtual void Stop() {
cout << "bicycle is stopped..." << endl;
}
};
class motorcar : public vehicle {
public:
virtual void Run() {
cout << "motorcar is running..." << endl;
}
virtual void Stop() {
cout << "motorcar is stopped..." << endl;
}
};
class motorcycle : public bicycle, public motorcar {
public:
virtual void Run() {
cout << "motorcycle is running..." << endl;
}
virtual void Stop() {
cout << "motorcycle is stopped..." << endl;
}
};
int main() {
vehicle v, *pv;
bicycle by;
motorcar mc;
motorcycle mcy;
// 通过对象名来调用各成员函数
v.Run();
v.Stop();
by.Run();
by.Stop();
mc.Run();
mc.Stop();
mcy.Run();
mcy.Stop();
cout << "---------------------------------------" << endl;
// 通过指针来调用各成员函数
pv = &v;
pv->Run();
pv->Stop();
pv = &by;
pv->Run();
pv->Stop();
pv = &mc;
pv->Run();
pv->Stop();
pv = м
pv->Run();
pv->Stop();
return 0;
}
```
输出结果为:
```
vehicle is running...
vehicle is stopped...
bicycle is running...
bicycle is stopped...
motorcar is running...
motorcar is stopped...
motorcycle is running...
motorcycle is stopped...
---------------------------------------
vehicle is running...
vehicle is stopped...
bicycle is running...
bicycle is stopped...
motorcar is running...
motorcar is stopped...
motorcycle is running...
motorcycle is stopped...
```
从输出结果可以看出,通过对象名或者指针来调用成员函数,都能够正常执行。当将`Run()`和`Stop()`函数声明为虚函数时,输出结果不会发生变化。这是因为当函数被声明为虚函数时,调用的是对象所指向的实际类型的函数,而不是指针所指向的类型的函数。因此,无论是通过对象名还是指针来调用,都能够正常执行。
阅读全文