fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class A
  5. {
  6. public:
  7. int x;
  8. int y;
  9. virtual int add() = 0;
  10. };
  11.  
  12. class B
  13. {
  14. public:
  15. int a;
  16. int b;
  17. virtual int sub() = 0;
  18. };
  19.  
  20. class C : public A, public B
  21. {
  22. public:
  23. C() { x = 1; y = 2; z = 3; a = 4; b = 5; c = 6; }
  24. int c;
  25. int z;
  26. virtual int add() { return a + z; }
  27. virtual int sub() { return c - x; }
  28. int mul() { return b * y; };
  29. };
  30.  
  31. class D : public A, public B
  32. {
  33. public:
  34. D() { x = 1; y = 2; z = 3; a = 4; b = 5; c = 6; }
  35. int c;
  36. int z;
  37. virtual int add() { return a + z; }
  38. virtual int sub() { return x - c; } // sub 做的事情不一樣
  39. int mul() { return b * y; };
  40. };
  41.  
  42. int main()
  43. {
  44. A *p = new D; // 這裡視情況可能建立 C 或 D
  45. cout << p->add() << endl;
  46. cout << ((C *)p)->sub() << endl;
  47. cout << ((C *)p)->mul() << endl;
  48. }
  49.  
Success #stdin #stdout 0.01s 2856KB
stdin
Standard input is empty
stdout
7
-5
10