车基类派生出自行车类和汽车类再从自行车类和汽车类派生摩托车(多态).cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <iostream>
  2. using namespace std;
  3. class Vehicle {
  4. public:
  5. virtual void Run() {
  6. cout << "vehicle run!" << endl;
  7. }
  8. virtual void Stop() {
  9. cout << "vehicle stop!" << endl;
  10. }
  11. };
  12. class Bicycle : virtual public Vehicle {
  13. public:
  14. void Run() {
  15. cout << "bicycle run!" << endl;
  16. }
  17. void Stop() {
  18. cout << "bicycle stop!" << endl;
  19. }
  20. };
  21. class Motorcar : virtual public Vehicle {
  22. public:
  23. void Run() {
  24. cout << "motocar run!" << endl;
  25. }
  26. void Stop() {
  27. cout << "motocar stop!" << endl;
  28. }
  29. };
  30. class Motorcycle : public Bicycle, public Motorcar {
  31. public:
  32. void Run() {
  33. cout << "motocycle run!" << endl;
  34. }
  35. void Stop() {
  36. cout << "motocycle stop!" << endl;
  37. }
  38. };
  39. int main() {
  40. Vehicle v;
  41. v.Run();
  42. v.Stop();
  43. Bicycle b;
  44. b.Run();
  45. b.Stop();
  46. Motorcar m;
  47. m.Run();
  48. m.Stop();
  49. Motorcycle mc;
  50. mc.Run();
  51. mc.Stop();
  52. Vehicle* vp = &v;
  53. vp->Run();
  54. vp->Stop();
  55. vp = &b;
  56. vp->Run();
  57. vp->Stop();
  58. vp = &m;
  59. vp->Run();
  60. vp->Stop();
  61. vp = &mc;
  62. vp->Run();
  63. vp->Stop();
  64. return 0;
  65. }