[英]'A' : no appropriate default constructor available
我在跟蹤以下代碼中的錯誤時遇到了一些麻煩。 我已經運行了它,它說“'A':沒有合適的默認構造函數可用”。 沒有調用參數的構造函數到底在哪里?
#include<iostream>
using namespace std;
class A
{
int x;
public: A(int i) : x(i){}
int get_x() const { return x; }
};
class B : public A
{
int *y;
public: B(int i) :A(i){
y = new int[i];
for (int j = 0; j < i; j++) y[j] = 1;
}
B(B&);
int &operator[](int i) { return y[i]; }
};
B::B(B& a)
{
y = new int[a.get_x()];
for (int i = 0; i < a.get_x(); i++) y[i] = a[i];
}
ostream& operator<<(ostream &o, B a)
{
for (int i = 0; i < a.get_x(); i++)
o << a[i];
return o;
}
int main()
{
B b(5);
cout << b;
return 0;
}
B::B(B& a)
是一個構造函數。 由於它是一個構造函數,您需要構造B
的A
部分,因為A
沒有默認構造函數。 我相信您打算制作一個復制構造函數,如果是這樣,那就是:
B::B(const B& a) : A(a)
{
y = new int[a.get_x()];
for (int i = 0; i < a.get_x(); i++) y[i] = a[i];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.