Inheritance of C + + 's constructors

Source: Internet
Author: User

  
 
  1. #include <iostream>
  2. using namespace std;
  3. class Base1
  4. {
  5. public:
  6. Base1() = default;
  7. Base1(const string & str)
  8. {
  9. strValue = str;
  10. }
  11. string strValue;
  12. };
  13. class Base2
  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: public Base1, public Base2
  31. {
  32. public:
  33. using Base1::Base1;// 从Base1继承构造函数
  34. using Base2::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. return 0;
  53. }



From for notes (Wiz)

Inheritance of C + + 's constructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.