在调用基础 class 构造函数时声明默认构造函数

Declaring default constructor while invoking base class constructor

我正在尝试实现调用基础 class 构造函数的概念,并且 inheritance.I 已经编写了以下代码,但是当我没有为 [=15 声明默认构造函数时它会出错=] A,我想知道为什么会出现错误。

#include <iostream>
using namespace std;

class A
{
    int a;
    public:
    A() {} //Default Constructor
    A(int x)
    {
        a=x;cout<<a;
        cout<<"A Constructor\n";
    }
};
class B: virtual public A
{
    int b;
    public:
    B(int x)
    {
        b=x;cout<<b;
        cout<<"B Constructor\n";
    }
};
class C: virtual public A
{
    int c;
    public:
    C(int x)
    {
        c=x;cout<<c;
        cout<<"C Constructor\n";
    }
};
class D: public B,public C
{
    int d;
    public:
    D(int p,int q,int r,int s):A(p),B(q),C(r)
    {
        d=s;cout<<d;
        cout<<"D Constructor\n";
    }
};
int main()
{
    D d(1,2,3,4);
    return 0;
}

如果在子类中不调用超类的构造函数,超类必须有一个默认的构造函数,因为如果要创建B的实例,会自动创建一个超类的实例,即如果没有默认构造函数则不可能。

目前,让我们简化事情并忘记 类 CD.

的存在

如果构造一个B类型的对象为

B b(10);

它将使用 B::B(int)。在 B::B(int) 的实现中,BA 部分必须以某种方式初始化。你有:

B(int x)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

相当于:

B(int x) : A()
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

由于 A 没有默认构造函数,编译器正确地将其报告为错误。

您可以使用以下方法解决此问题:

B(int x) : A(0)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}

如果希望能够从 B 的构造函数向 A(int) 传递另一个值,您需要允许用户使用两个参数构造 B

B(int x, int y = 0) : A(y)
{
    b=x;cout<<b;
    cout<<"B Constructor\n";
}