2017-11-08 8 views
0

次のプログラムでは、基本クラスからクラスを派生させたいと思います。私のコードでは、すべてがOKであるようです。ただし、以下のプログラムでエラーが表示されています。エラーの原因とその修正方法を説明してください。C++継承:エラー:候補は1つの引数、0を期待します。

#include <iostream> 
using namespace std; 

struct Base 
{ 
    int x; 
    Base(int x_) 
    { 
     x=x_; 
     cout<<"x="<<x<<endl; 
    } 
}; 

struct Derived: public Base 
{ 
    int y; 
    Derived(int y_) 
    { 
     y=y_; 
     cout<<"y="<<y<<endl; 
    } 
}; 

int main() { 
    Base B(1); 
    Derived D(2); 
} 

これは誤りである:

Output: 

error: no matching function for call to 'Base::Base() 
Note: candidate expects 1 argument, 0 provided 
+0

基本クラスのコンストラクタには引数があります。したがって、派生クラスは基本クラスを適切に構築する必要があります。詳細については、C++の本を参照してください。 –

答えて

0

デフォルトコンストラクタ(すなわちBase::Base())はDerivedBaseサブオブジェクトを初期化するために使用されるが、いずれかBase有していません。

member initializer listを使用して、Baseのコンストラクタを使用する必要があります。例えば

struct Derived: public Base 
{ 
    int y; 
    Derived(int y_) : Base(y_) 
    //    ~~~~~~~~~~ 
    { 
     y=y_; 
     cout<<"y="<<y<<endl; 
    } 
}; 
関連する問題