且构网

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

从父类ctor调用重写的方法

更新时间:2022-12-29 09:23:56

在 C++ 中,正如您正确指出的那样,对象的类型是 A 直到 A 构造函数是完成的.对象在构造过程中实际上改变了类型.这就是使用 A 类的 vtable 的原因,所以 A::foo() 被调用而不是 B::foo().

In C++, as you correctly noted, the object is of type A until the A constructor is finished. The object actually changes type during its construction. This is why the vtable of the A class is used, so A::foo() gets called instead of B::foo().

在 Java 和 C# 中,自始至终都使用最派生类型的 vtable(或等效机制),即使在基类的构造过程中也是如此.所以在这些语言中,B.foo() 会被调用.

In Java and C#, the vtable (or equivalent mechanism) of the most-derived type is used throughout, even during construction of the base classes. So in these languages, B.foo() gets called.

请注意,一般不建议从构造函数中调用虚方法.如果您不是很小心,虚拟方法可能会假定对象是完全构造的,即使情况并非如此.在 Java 中,每个方法都是隐式虚拟的,您别无选择.

Note that it is generally not recommended to call a virtual method from the constructor. If you're not very careful, the virtual method might assume that the object is fully constructed, even though that is not the case. In Java, where every method is implicitly virtual, you have no choice.