子类创建对象时调用父类的构造函数:
1 #include <iostream> 2 using namespace std; 3 class Base 4 { 5 public: 6 Base():m_num(0){ 7 cout<<"this is Base()"<<endl; 8 } 9 Base(int val):m_num(val){ 10 cout<<"this is Base(int val)"<<endl; 11 } 12 private: 13 int m_num; 14 }; 15 16 class BaseChild:public Base 17 { 18 public: 19 BaseChild(){ 20 cout<<"this is BaseChild()"<<endl; 21 } 22 BaseChild(int val):Base(val){ 23 cout<<"this is BaseChild(val)"<<endl; 24 } 25 }; 26 27 int main(int argc,char *argv[]) 28 { 29 BaseChild child1; 30 BaseChild child2(5); 31 return 0; 32 }
父类的构造函数无法继承,故必须在子类构造函数初始化列表中引用,否则将调用父类的默认构造函数
构造函数中有默认参数时:
1 #include <iostream> 2 using namespace std; 3 class Base 4 { 5 public: 6 Base(int val):m_num(val){ 7 cout<<"this is Base(int val)"<<endl; 8 } 9 private: 10 int m_num; 11 }; 12 13 class BaseChild:public Base 14 { 15 public: 16 BaseChild(int val=14):Base(val){ 17 cout<<"this is BaseChild(val)"<<endl; 18 } 19 }; 20 21 int main(int argc,char *argv[]) 22 { 23 BaseChild child1; 24 return 0; 25 }
注意,如果子类构造函数中没有默认参数,就会报错,因为父类、子类中都没有定义无参数的构造函数;而若父类、子类加上无参数的构造函数后,也会报错,因为会产生二义性问题,编译器不知道用户想调用哪个构造函数
参考:
c++构造函数初始化类对象
https://blog.csdn.net/weixin_43891901/article/details/89227108
c++子类构造函数初始化
https://www.cnblogs.com/clovershell/p/10246629.html
c++二义性问题