sco*_*ozy 8 c++ constructor virtual-inheritance ctor-initializer
我的理解,例如阅读本文,是派生类的构造函数不会调用其虚拟基类的构造函数。
这是我制作的一个简单示例:
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;
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,构造函数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
Run Code Online (Sandbox Code Playgroud)
我确定我误解或做错了一些非常基本的事情,但我不知道是什么。
构造虚拟基的构造函数。它是有条件建造的。即最底层派生类的构造函数调用虚基类的构造函数。如果 - 这是条件 - 具有虚拟基类的派生类不是所构造对象的具体类,那么它不会构造虚拟基类,因为它已经由具体类构造了。但否则它将构建虚拟基地。
因此,您必须在所有派生类的构造函数中正确初始化虚拟基类。您必须知道,如果具体类不是您正在编写的类,则不一定会发生特定的初始化。编译器不知道也不可能知道您是否会创建这些中间类的直接实例,因此它不能简单地忽略它们损坏的构造函数。
如果您将这些中间类抽象化,那么编译器就会知道它们永远不是最具体的类型,因此不需要它们的构造函数来初始化虚拟基类。
| 归档时间: |
|
| 查看次数: |
204 次 |
| 最近记录: |