菱形继承是多重继承中跑不掉的,Java拿掉了多重继承,辅之以接口。C++中虽然没有明确说明接口这种东西,但是只有纯虚函数的类可以看作Java中的接口。在多重继承中建议使用“接口”,来避免多重继承中可能出现的各种问题。

    image.png
    image.png
    image.png
    示例代码:

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