gpt4 book ai didi

c++ - 为什么派生类的构造函数要在C++中初始化虚拟基类?

转载 作者:行者123 更新时间:2023-12-03 06:49:36 24 4
gpt4 key购买 nike

我的理解,比如阅读this,是派生类的构造函数不调用其虚拟基类的构造函数。
这是我制作的一个简单示例:

class A {
protected:
A(int foo) {}
};

class B: public virtual A {
protected:
B() {}
};

class C: public virtual A {
protected:
C() {}
};

class D: public B, public C {
public:
D(int foo, int bar) :A(foo) {}
};


int main()
{
return 0;
}
出于某种原因,构造函数 B::B()C::C()正在尝试初始化 A (在我的理解中,此时应该已经被 D 初始化了):
$ g++ --version
g++ (GCC) 10.2.0
Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ test.cpp
test.cpp: In constructor ‘B::B()’:
test.cpp:8:13: error: no matching function for call to ‘A::A()’
8 | B() {}
| ^
test.cpp:3:9: note: candidate: ‘A::A(int)’
3 | A(int foo) {}
| ^
test.cpp:3:9: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: ‘constexpr A::A(const A&)’
1 | class A {
| ^
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: ‘constexpr A::A(A&&)’
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
test.cpp: In constructor ‘C::C()’:
test.cpp:13:13: error: no matching function for call to ‘A::A()’
13 | C() {}
| ^
test.cpp:3:9: note: candidate: ‘A::A(int)’
3 | A(int foo) {}
| ^
test.cpp:3:9: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: ‘constexpr A::A(const A&)’
1 | class A {
| ^
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: ‘constexpr A::A(A&&)’
test.cpp:1:7: note: candidate expects 1 argument, 0 provided
我确定我误解或做错了一些非常基本的事情,但我不知道是什么。

最佳答案

虚基的构造函数建。它是有条件地构建的。即最派生类的构造函数调用虚基类的构造函数。如果 - 这是条件 - 具有虚拟基类的派生类不是构造对象的具体类,那么它将不会构造虚拟基类,因为它已经被具体类构造了。但否则它将构建虚拟基地。
因此,您必须在所有派生类的构造函数中正确初始化虚拟基类。您只需要知道,如果具体类不是您正在编写的类,则不一定会发生特定的初始化。编译器不会也无法知道您是否会创建这些中间类的直接实例,因此它不能简单地忽略它们损坏的构造函数。
如果你使这些中间类抽象,那么编译器就会知道它们永远不是最具体的类型,因此它们的构造函数不需要初始化虚拟基类。

关于c++ - 为什么派生类的构造函数要在C++中初始化虚拟基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64655841/

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