从构造函数调用虚函数
也许我错了,但这似乎是一个非常基本的问题。 突然我的继承链停止了工作。 编写一个小型的基本测试应用程序证明是我错了(所以我不能责怪编译器)。
我有一个基类,具有虚函数中的默认行为。 子类从中派生并改变行为。
#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
当创建 Child 实例时,为什么调用 Base::print()? 我认为通过使用virtual关键字,可以为派生类替换该函数。
我在什么时候让自己变得困惑了?
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;
}
This prints:
base
base
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在构造函数中调用虚拟方法,这是行不通的,因为子类尚未完全初始化。
另请参阅此 StackOverflow 问题。
You are calling a virtual method in the constructor, which is not going to work, as the child class isn't fully initialized yet.
See also this StackOverflow question.
虽然您当前的问题是其他人提到的构造函数的虚拟方法调用,但我注意到您没有将析构函数设为虚拟。 这通常是一件坏事。 在您的情况下,析构函数是 nop,并且没有成员是具有析构函数的对象,...但是如果您的代码发生更改,那么很容易发生不好的事情。
Although your current problem is the virtual method call from a constructor that others have mentioned, I noticed that you didn't make the destructors virtual. That's normally a bad thing. In your case, the destructors are nops and there are no members that are objects with destructors,... but if your code changes then it's easy for bad things to happen.