构造函数中调用虚函数时,父类构造函数调用的是父类的虚函数,子类构造函数调用的是子类的虚函数。
父类构造函数并没有遵循虚函数调用机制,调用具体子类的虚函数,是因为调用父类构造函数时,子类对象还没有构造好。
#include <stdio.h>
class Base
{
public:
Base(){printf("Base ctor\n");g();};
virtual void f(){printf("Base::f\n");};
void g() {
f();
};
};
class Derived:public Base
{
public:
Derived(){printf("Derived ctor\n"); f();};
void f(){printf("Derived::f\n");};
};
int main()
{
Derived d;
d.g();
return 0;
}
本文探讨了在构造函数中调用虚函数时的行为差异,指出父类构造函数会调用父类的虚函数而子类构造函数则调用子类的虚函数。通过一个C++代码示例说明了这一现象的原因。
1779

被折叠的 条评论
为什么被折叠?



