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. B* getBptr() { return (B *)this; } // 新增了這一行
  31. };
  32.  
  33. int main()
  34. {
  35. A *p = new C;
  36. cout << p->add() << endl;
  37. cout << ((C*)p)->getBptr()->sub() << endl; // 修改了這一行
  38. cout << ((C *)p)->mul() << endl;
  39. }
  40.  
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
7
5
10