关键词搜索

源码搜索 ×
×

使用C++多重继承时要小心

发布2013-05-26浏览8141次

详情内容

       在Java里,没有多重继承,在C++里面有,但是,在用的时候,要小心。先看一个错误程序:

  1. #include <iostream>
  2. using namespace std;
  3. class Father
  4. {
  5. public:
  6. void claim()
  7. {
  8. cout << "Father is good!" << endl;
  9. }
  10. };
  11. class Mother
  12. {
  13. public:
  14. void claim()
  15. {
  16. cout << "Mother is good!" << endl;
  17. }
  18. };
  19. class Child : public Father, public Mother
  20. {
  21. };
  22. int main()
  23. {
  24. Child c;
  25. c.claim(); // 二义性
  26. return 0;
  27. }
      可以改为:

  1. #include <iostream>
  2. using namespace std;
  3. class Father
  4. {
  5. public:
  6. void claim()
  7. {
  8. cout << "Father is good!" << endl;
  9. }
  10. };
  11. class Mother
  12. {
  13. public:
  14. void claim()
  15. {
  16. cout << "Mother is good!" << endl;
  17. }
  18. };
  19. class Child : public Father, public Mother
  20. {
  21. };
  22. int main()
  23. {
  24. Child c;
  25. c.Father::claim();
  26. c.Mother::claim();
  27. return 0;
  28. }
     

       另外,在菱形继承时,也会出现类似问题,解决方式是采用虚继承。




相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载