这是代码:
#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/