gpt4 book ai didi

c++ - 从构造函数调用虚函数

转载 作者:太空狗 更新时间:2023-10-29 23:21:49 29 4
gpt4 key购买 nike

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

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

#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 关键字,可以为派生类替换函数。

我什么时候把自己弄糊涂了?

最佳答案

你在构造函数中调用了一个虚方法,它不会起作用,因为子类还没有完全初始化。

另见 this StackOverflow question .

关于c++ - 从构造函数调用虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/507043/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com