這里總結下C++中關于子類繼承父類后構造方法的調用問題
1.首先看下這種情況
//父類
class parent
{
public:
parent(int b){cout<<"parent has parame b = "<<b<<endl;}
};
//子類
class child : public parent
{
public:
child(int a){cout<<"child has parame a = "<<a<<endl;}
};
//main函數
#include "child.h"
int main()
{
child a(5);
}
父類和子類各有一個帶整形形參的構造方法,此時編譯程序,是有錯誤的,如下
F:\qt_program\cpp_test\child.h:-1: In constructor 'child::child(int)':
F:\qt_program\cpp_test\child.h:9: error: no matching function for call to 'parent::parent()'
child(int a){cout<<"child has parame a = "<<a<<endl;}
什么意思呢?就是說在構造child類時候,調用了父類構造方法parent,但是這個構造方法必須不帶參數,
而父類中是沒有這么一個方法的,所以會產生這個錯誤。
2.我們把父類改為如下形式,加入一個不帶形參的構造方法
class parent
{
public:
parent(){cout<<"parent no parame"<<endl;}
parent(int b){cout<<"parent has parame b = "<<b<<endl;}
};
那么此時就編譯通過了,輸出信息為:
parent no parame
parent has parame b = 5
也就說在子類實例化過程中,首先默認調用了父類無參構造函數,然后再調用子類構造函數
3.那么如果我們子類想調用父類的帶參構造函數怎么辦呢?就需要對子類作如下修改:
class child : public parent
{
public:
child(int a):parent(6)
{cout<<"child has parame a = "<<a<<endl;}
};
這樣子類在構造時候,會默認先調用父類帶參構造,然后在調用子類相應構造方法