C++多级虚继承编译问题

C++ Multi-level virtual Inheritance compilation problem

我正在开发一个 C++ 项目,其中我使用了多级继承。

这是我的示例代码:

class ClassA
{
public:
    ClassA(int a,int b) : sum(a + b) {}
    virtual ~ClassA() = default;

    int sum;
};

class ClassB : virtual public ClassA
{
public:
    ClassB(int a, int b, int c) : ClassA(a, b), c(c) {}

    int c;
};

class ClassC : virtual public ClassB
{
public:
    ClassC(int a,int b,int c) : ClassB(a, b, c) {}
};

int main()
{
    ClassC objC(1, 2, 3);

    std::cout << "sum=" << objC.sum << std::endl;
    std::cout << "c=" << objC.c << std::endl;
}

谁能解释一下这段代码有什么问题。

error: no matching function for call to 'ClassA::ClassA()'
ClassC(int a,int b,int c) : ClassB(a, b, c) {}

来自Derived class

All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its member initializer list:

所以你的class应该修改为:

ClassC::ClassC(int a, int b,int c):ClassA(a, b), ClassB(a, b, c) {}