派生類構造函數
阿新 • • 發佈:2019-04-09
一個 pub code for private ive 找不到 類的構造函數 ()
1 #include<iostream> 2 using namespace std; 3 4 class Base1{ 5 public: 6 Base1(int i){ 7 cout<<"Base1 "<<i<<endl; 8 } 9 }; 10 11 class Base2{ 12 public: 13 Base2(int j){ 14 cout<<"Base2 "<<j<<endl;15 } 16 }; 17 18 class Derived:public Base2, public Base1{ 19 public: 20 Derived(int a,int b,int c,int d):Base1(a),member1(c),member2(d),Base2(b){} 21 private: 22 Base1 member1; 23 Base2 member2; 24 }; 25 26 int main() 27 { 28 Derived obj(1,2,3,4); 29 }
這是一個派生類構造函數的例子,照書上打的,簡化了一些。
在Derived類構造函數中,先調用基類的構造函數,然後調用內嵌對象的構造函數。
調用順序先按這裏的順序來
class Derived:public Base2, public Base1{……}
先是Base2,再是Base1
然後是按這邊的順序
private:
Base1 member1;
Base2 member2;
先是Base1,再是Base2
1 #include<iostream> 2 using namespacestd; 3 4 class Base1{ 5 public: 6 Base1(int i){ 7 cout<<"Base1 "<<i<<endl; 8 } 9 }; 10 11 class Base2{ 12 public: 13 Base2(int j){ 14 cout<<"Base2 "<<j<<endl; 15 } 16 }; 17 18 class DD:public Base1, public Base2{ 19 public: 20 DD(int a,int b):Base1(a),Base2(b){} 21 private: 22 Base1 member1; 23 Base2 member2; 24 }; 25 26 int main() 27 { 28 DD obj(1,2); 29 }
如果我把代碼改成這樣,只初始化基類,而不初始化內嵌對象,就會報錯no matching function for call to ‘Base1::Base1()’
我在把代碼改一下,變成這樣
1 #include<iostream> 2 using namespace std; 3 4 class Base1{ 5 public: 6 Base1(int i=0){ 7 cout<<"Base1 "<<i<<endl; 8 } 9 }; 10 11 class Base2{ 12 public: 13 Base2(int j=0){ 14 cout<<"Base2 "<<j<<endl; 15 } 16 }; 17 18 class DD:public Base1, public Base2{ 19 public: 20 DD(int a,int b,int c,int d):member1(c),member2(d){} 21 private: 22 Base1 member1; 23 Base2 member2; 24 }; 25 26 int main() 27 { 28 DD obj(1,2,3,4); 29 }
也就是把基類的構造函數的參數初始化了,這也相當於一種默認構造函數。編譯就通過了。
應該是如果初始化列表裏的初始化不完全的話,程序就會去找類的默認構造函數,因為之前代碼的類的構造函數,有參數,且沒有初始化,所以就找不到默認構造函數,於是報錯。
派生類構造函數