问题描述
#include <iostream> using namespace std; struct A{ A() {cout << "A" << endl;} A(int a) {cout << "A+" << endl;} }; struct B : virtual A{ B() : A(1) {cout << "B" << endl;} }; struct C : virtual A{ C() : A(1) {cout << "C" << endl;} }; struct D : virtual A{ D() : A() {cout << "D" << endl;} }; struct E : B, virtual C, D{ E(){cout << "E" << endl;} }; struct F : D, virtual C{ F(){cout << "F" << endl;} }; struct G : E, F{ G() {cout << "G" << endl;} }; int main(){ G g; return 0; }
计划打印:
A C B D E D F G
我想知道应该使用什么规则来确定构造函数的调用顺序。感谢。
I would like to know what rules should I use to determine in what order constructors get called. Thanks.
推荐答案
虚拟基础子对象首先由最大派生类构造,这是有意义的唯一方式,因为在运行时(因此虚拟)直到对象构造,虚拟基础与最大导出对象的关系是未知的。
Virtual base subobjects are constructed first, by the most-derived class, before any other bases. This is the only way that makes sense, since the relation of the virtual bases to tbe most-derived object is not known until object construction, at runtime (hence "virtual"). All intermediate initializers for virtual bases are ignored.
那么,你的虚拟基础是什么? G 源自 E 和 F 。 E 从 C 中实际派生,后者又从 A ,因此 A , C 是第一个。接下来, F 不会添加任何其他虚拟库。接下来, E 有非虚基数 B 和 D ,按顺序构建,然后 E 完成。然后 F 的非虚拟基础 D 和 F 完成。最后, G 已完成。
So, what are your virtual bases? G derives from E and F. E derives virtually from C, which in turn derives virtually from A, so A, C are first. Next, F doesn't add any further virtual bases. Next, E has non-virtual bases B and D, in that order, which are constructed next, and then E is complete. Then comes F's non-virtual base D, and F is complete. Finally, G is complete.
总而言之,它是虚拟基础 code>, C ,则非虚拟基础 B , code>, E 和 D ,然后 G 本身。
All in all, it's virtual bases A, C, then non-virtual bases B, D, E and D, F, and then G itself.
这篇关于调用构造函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!