从构造函数调用虚函数 [英] Virtual function invocation from constructor
问题描述
也许我错了,但这似乎是一个非常基本的问题。突然我的继承链停止工作。写一个小的基本测试应用程序证明是我是错误的(所以我不能怪编译器)。
Maybe I am wrong, but this seems to be a very basic question. Suddenly my inheritance chain stopped working. Writing a small basic test application proved that it was me that was wrong (so I can't blame the compiler).
我有一个基类,在虚函数中。
I have a base class, with the default behavior in a virtual function. A child class derives from that and changes the behavior.
#include <iostream>
class Base
{
public:
Base() { print(); }
~Base() {}
protected:
virtual void print() { std::cout << "base\n"; }
};
class Child : public Base
{
public:
Child() {}
~Child() {}
protected:
virtual void print() { std::cout << "child\n"; }
};
int main()
{
Base b;
Child c;
}
打印:
base
base
是创建,为什么是Base :: print()调用?我认为通过使用virtual关键字,该函数可以替换为派生类。
When a Child instance is created, why is Base::print() called? I thought that by using the virtual keyword, the function can be replaced for the derived class.
我在什么时候感到困惑?
At what point did I get myself confused?
推荐答案
另请参见这个StackOverflow问题。
这篇关于从构造函数调用虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!