2017-04-13 45 views
-1

我試圖解決這個錯誤,但我沒有做什麼..得到錯誤的呼叫沒有匹配功能,飛艇飛艇

#include<iostream> 
#include<string> 
using namespace std; 
class AirShip{ 
private: 
    int passenger; 
    double cargo; 
public: 
    AirShip(int x,double y) 
    { 
     passenger=x; 
     cargo=y; 
    } 

    void show() 
    { 
     cout<<"passenger="<<passenger<<endl; 
     cout<<"cargo="<<passenger<<endl; 
    } 
}; 
class AirPlane: protected AirShip{ 
private: 
    string engine; 
    double range; 
public: 
    AirPlane(string a,double b) 
    { 
     engine=a; 
     range=b; 
    } 
void show() 
{ 
    cout<<"engine="<<engine<<endl; 
    cout<<"range="<<range<<endl; 
} 
}; 

的錯誤是: 錯誤:呼叫沒有匹配功能到'AirShip :: AirShip()' 需要幫助... 我稍後會把主要功能,因爲錯誤在這裏。

+0

相關:http://stackoverflow.com/questions/4981241/no-default-constructor-exists-for-class –

+0

您是否曾嘗試爲'AirShip'添加一個空的構造函數,因爲根據錯誤似乎是什麼失蹤。 – moondaisy

+0

是的,我需要調用一個無參數的構造函數。它工作的方式太。謝謝你 –

回答

3

當您創建AirPlane時,您還隱式創建了AirShip的一部分。你可能也寫的構造是這樣的:

AirPlane(string a,double b) : AirShip() 
{ 
    engine=a; 
    range=b; 
} 

然而,AirShip沒有默認構造函數。你基本上有兩種選擇:1)提供一個默認的構造函數。默認構造函數是可以不帶參數調用的構造函數。例如,您可以提供乘客和貨物數量的默認參數。但是,我不會推薦。 Imho最好是正確地初始化構造函數中的所有成員,並且默認值不是大多數時候想要的。

B)正確初始化AirPlane例如在AirShip部分...

AirPlane(string a,double b, int x, double y) : 
    AirShip(x,y),engine(a),range(b) 
{} 

...並使用初始化列表也爲其他成員。

+0

我看到它初始化,但我應該如何調用主函數...我試圖瞭解C++ ..我寫了這樣的主要功能---- int main(void){ AirPlane ap1(200,40.550,「jets」,500.560); AirPlane ap; ap.show(); return 0; } 我再次得到了同樣的錯誤....所以,我一定要調用構造飛艇@主要funtion太 –

+0

@johnerjubair你仍然有'飛機AP;'在'main',即此時你試圖調用'Airplane'的默認構造函數,這次你的選擇是A)爲'Airplane'提供默認的構造函數(不會提示)B)只要按照'ap1(200,40.550, 「噴氣機」,500.560)',例如'ap(100,1.0,「waterbaloon」,0.0)' – user463035818

+0

謝謝。它工作得很好。這教給我的東西:) –

0

由於您AirPlane -class從AirShip派生,它需要初始化基類爲好,無論是通過顯式調用AirShip -constructor或通過(甚至含蓄地)稱爲AirShip -default構造。

但是,你AirShip類不提供一個默認的構造函數(這可以隱式調用),和您的AirPlane(string a,double b) { ... } -constructor沒有顯式調用任何其它AirShip -constructor。

因此,要麼在AirShip處定義默認構造函數,要麼引入基類的顯式初始化,例如,通過編寫AirPlane(string a,double b) : AirShip(0,0) {...}

+0

謝謝你的工作! :) –