考虑这个演示程序:
#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)
我希望调用 toobj.f()
会导致调用,Base::obj.f()
因为派生类没有定义它,然后会导致调用Derived::obj.f(0)
每个类 Base 中的定义。
我在这里做错了什么?有没有办法做到这一点?具体来说,我希望调用obj.f()
返回 10。
(另外请注意,我意识到我可以使用默认参数来解决这个问题,但这段代码只是我的问题的一个简明示例,所以请不要告诉我使用默认参数。)
谢谢。