考虑这个演示程序:
#include <stdio.h>
class Base
{
public:
virtual int f(int) =0;
virtual int f(){ return f(0); }
virtual ~Base(){ }
};
class Derived : public Base
{
public:
int f(int i)
{
return (10 + i);
}
};
int main(void)
{
Derived obj;
printf("%d\n", obj.f(1)); // This works, and returns 11
printf("%d\n", obj.f()); // Adding this line gives me the error listed below
}
这让我遇到了以下编译错误:
virtualfunc.cpp: In function ‘int main()’:
virtualfunc.cpp:25:26: error: no matching function for call to ‘Derived::f()’
virtualfunc.cpp:15:9: note: candidate is: virtual int Derived::f(int)
我希望调用
obj.f()
时,会调用Base::obj.f()
,因为派生类没有定义它,这样将按照类Base中的定义导致调用Derived::obj.f(0)
。请问我做错了什么?有什么办法可以解决这个问题吗?具体来说,我希望调用obj.f()
返回10。(还请注意,我知道可以使用默认参数来解决这个问题,但是这段代码仅仅是我遇到的问题的简明示例,请不要告诉我使用默认参数。)谢谢。
Derived
中的f
函数“隐藏”了在Base
中定义的其他函数。这就是为令你出现此错误的原因。 - Kiril Kirovusing Base::f;
解决了它。谢谢! - jedwards