且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-12-04 01:05:21

已构建虚拟库的构造器.它是有条件构造的.即,最派生类的构造函数调用虚拟基数的构造函数.如果-这是条件-具有虚拟基础的派生类不是所构造对象的具体类,则它将不会构造虚拟基础,因为它已经由具体类构造了.但是否则它将构建虚拟基础.

The constructor of virtual base is constructed. It is constructed conditionally. That is, the constructor of the most derived class calls the constructor of the virtual base. If - this is the condition - the derived class with virtual base is not the concrete class of the constructed object, then it will not construct the virtual base because it has already been constructed by the concrete class. But otherwise it will construct the virtual base.

因此,您必须在所有派生类的构造函数中正确初始化虚拟基类.您只必须知道,如果具体类不是您正在编写的类,则不一定要进行特定的初始化.编译器不会也不知道您是否会创建这些中间类的直接实例,因此它不能简单地忽略它们损坏的构造函数.

So, you must correctly initialise the virtual base class in constructors of all derived classes. You simply must know that specific initialisation doesn't necessarily happen in case the concrete class is not the one which you are writing. The compiler doesn't and cannot know whether you will ever create direct instances of those intermediate classes, so it cannot simply ignore their broken constructors.

如果将那些中间类抽象化,那么编译器将知道它们永远不是最具体的类型,因此不需要初始化虚拟基的构造函数.

If you made those intermediate classes abstract, then the compiler would know that they are never the most concrete type and thus their constructor would not be required to initialise the virtual base.