从构造函数调用虚函数

发布于 2024-07-13 06:54:33 字数 647 浏览 7 评论 0原文

也许我错了,但这似乎是一个非常基本的问题。 突然我的继承链停止了工作。 编写一个小型的基本测试应用程序证明是我错了(所以我不能责怪编译器)。

我有一个基类,具有虚函数中的默认行为。 子类从中派生并改变行为。

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三五鸿雁 2024-07-20 06:54:33

您在构造函数中调用虚拟方法,这是行不通的,因为子类尚未完全初始化。

另请参阅此 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.

遗失的美好 2024-07-20 06:54:33

虽然您当前的问题是其他人提到的构造函数的虚拟方法调用,但我注意到您没有将析构函数设为虚拟。 这通常是一件坏事。 在您的情况下,析构函数是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文