0

我是C++中的新繼承人,並決定嘗試一些實驗來了解這個主題。在多繼承中沒有匹配的功能

下面的代碼顯示類我創建層次:

classes.h

class base 
{ 
protected: 
    int _a; 
    int _b; 
    int _c;; 
    base(int b, int c); 
}; 

class sub_one : public virtual base 
{ 
public: 
    sub_one(int a, int b) : base(a, b) 
    { 
     // do some other things here 
    } 

    // other members 
}; 


class sub_two : public virtual base 
{ 
protected: 
    int _d; 
public: 
    sub_two(int a, int b, int c = 0) : base(a, b) 
    { 
     // do something 
    } 

    // other members 
}; 


class sub_three : public sub_one, public sub_two 
{ 
private: 
    bool flag; 
public: 
    sub_three(int a, int b, int c = 0) : base(a, b) 
    { 
     // do something  
    } 
}; 

classes.c

base::base(int a, int b) 
{ 
    // ... 
} 

編譯器顯示我的信息:

調用sub_one時沒有匹配函數:: sub_one()

用於呼叫到sub_one :: sub_one()

沒有匹配函數調用sub_two :: sub_two()

沒有匹配函數調用sub_two沒有匹配的功能:: sub_two()

我只是無法找出什麼是錯的。

+0

'sub_three'構造函數初始化'base',但忘了初始化的另外兩個它的基類。 'sub_one'和'sub_two'都沒有默認構造函數,因此您需要在'sub_three'的構造函數初始化列表中明確列出它們。 –

回答

2
sub_three(int a, int b, int c = 0) : base(a, b) 
{ 
    // do something  
} 

等同於:

sub_three(int a, int b, int c = 0) : base(a, b), sub_one(), sub_two() 
{ 
    // do something  
} 

由於在sub_onesub_two沒有這樣的構造函數,編譯器報告錯誤。您可以將默認構造函數添加到sub_onesub_two以刪除錯誤。

1

sub_three構造函數初始化base,並調用sub_onesub_two默認構造函數不存在,你可能需要

class sub_three : public sub_one, public sub_two 
{ 
private: 
    bool flag; 
public: 
    sub_three(int a, int b, int c = 0) 
     : base(a, b), sub_one(a,b), sub_two(a,b,c), flag(false) 
    { 
     // do something  
    } 
};