gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:56:02 25 4
gpt4 key购买 nike

我正在开发一个 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:

所以你的类应该修改为:

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

关于C++多级虚继承编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52780732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com