'A':没有合适的默认构造函数可用

'A' : no appropriate default constructor available

本文关键字:默认 构造函数      更新时间:2023-10-16

我在跟踪下面这段代码中的一个bug时遇到了一点麻烦。我已经运行了它,它说"'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)

是构造函数。由于它是一个构造函数,您需要构造BA部分,因为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];
}