C++之构造函数的继承

  1. #include<iostream>
  2. usingnamespace std;
  3. classBase1
  4. {
  5. public:
  6. Base1()=default;
  7. Base1(const string & str)
  8. {
  9. strValue = str;
  10. }
  11. string strValue;
  12. };
  13. classBase2
  14. {
  15. public:
  16. Base2()=default;
  17. Base2(const string & str)
  18. {
  19. strVal2nd = str;
  20. }
  21. string strVal2nd;
  22. };
  23. /**
  24. * 一般情况下子类并不继承父类的构造函数
  25. * 仅仅是在初始化父类的成员变量时调用父类的构造函数
  26. * C++11允许通过下述语句来继承父类的构造函数
  27. * using ParentClass::ParentClass;
  28. * 这时需要注意,不要因为继承不同基类的构造函数而引起二义性
  29. */
  30. class D:publicBase1,publicBase2
  31. {
  32. public:
  33. usingBase1::Base1;// 从Base1继承构造函数
  34. usingBase2::Base2;// 从Base2继承构造函数
  35. /**
  36. * 如果同时继承了上述两个基类的构造函数
  37. * 则D必须实现自己的构造函数从而覆盖继承的构造函数
  38. */
  39. D()=default;
  40. D(const string & str)// 这个构造函数不能少
  41. {
  42. D(str, str);
  43. }
  44. D(const string & str1,const string & str2):Base1(str1),Base2(str2)
  45. {
  46. }
  47. };
  48. int main()
  49. {
  50. D d("Hello","World");
  51. cout << d.strValue <<"\t"<< d.strVal2nd << endl;
  52. return0;
  53. }
 





posted @ 2015-07-16 19:03  指上弹兵赵小括  阅读(967)  评论(0编辑  收藏  举报