定义Base和Derived如下:
class Base {
public:
virtual int f1(int a) const = 0;
virtual int f2(int a, int b) const { return a+b;}
};
class Derived : public Base {
public:
int f1(int a) const { return a; }
};
int main() {
Derived obj;
cout << obj.f1(1) << endl;
cout << obj.f2(1, 2) << endl;
}
结果是:
1
3
obj.f1(1)使用来自Derived的f1实现,而obj.f2(1, 2)使用从Base继承的实现,这正是我想要的。
现在,我想让这两个函数具有相同的名称f,因此基类在有两个参数时提供了一个实现,派生类必须实现单参数版本(这就是为什么它是纯虚拟的)。
然而,如果我这样做(只需将f1和f2重命名为f):
class Base {
public:
virtual int f(int a) const = 0;
virtual int f(int a, int b) const { return a + b;}
};
class Derived : public Base {
public:
int f(int a) const { return a; }
};
int main() {
Derived obj;
cout << obj.f(1) << endl;
cout << obj.f(1, 2) << endl;
}
I get the following error:
20:23: error: no matching function for call to 'Derived::f(int, int)'
20:23: note: candidate is:
14:13: note: virtual int Derived::f(int) const
14:13: note: candidate expects 1 argument, 2 provided
为什么呢?难道不能进行这种重载吗?