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. }
 





转载于:https://www.cnblogs.com/fengkang1008/p/4652216.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值