gpt4 book ai didi

c++ - 从 C++ 中的基方法调用重写的子方法

转载 作者:行者123 更新时间:2023-11-28 06:20:31 26 4
gpt4 key购买 nike

代码如下:

#include <iostream>
class A
{
public:
void foo()
{
cout<<"this is base foo()"<<endl;
}

void callfoo()
{
foo();
}
};

class B: public A
{
public:
void foo()
{
cout<<"this is child foo()"<<endl;
}
};

int main()
{
B b;
b.callfoo(); //Output: "this is base foo()"
b.foo(); //Output: "this is child foo()"
return 0;
}

现在,当我调用 b.callfoo() 时,不是调用子类 B 的 foo(),而是调用 callfoo()基类 A 的 foo()。在 B 类中,我们用新的实现覆盖了 foo(),但 callfoo() 仍在调用基础 foo() 而不是子 foo()。如果您对此行为有任何解释,请提供帮助。

最佳答案

在 C++ 中,您需要通过添加 virtual 关键字将方法显式标记为可重写:virtual void foo()

关于c++ - 从 C++ 中的基方法调用重写的子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376664/

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