查看如下代码段:
[c light=”false” toolbar=”false”]
#include<iostream>
using namespace std;
class B {
public:
int f(int i) { cout << “f(int): “; return i+1; }
// …
};
class D : public B {
public:
double f(double d) { cout << “f(double): “; return d+1.3; }
// …
};
int main()
{
D* pd = new D;
cout << pd->f(2) << ‘\n’;
cout << pd->f(2.3) << ‘\n’;
}
[/c]
输出是:
f(double): 3.3
f(double): 3.6
而不是:
f(int): 3 f(double): 3.6
原因C++之父Stroustrup阐述如下:
there is no overload resolution between D and B. The compiler looks into the scope of D,finds the single function “double f(double)” and calls it.It never bothers with the (enclosing) scope of B. In C++, there is no overloading across scopes – derived class scopes are not an exception to this general rule.
如果你一定要让子类可以重载父类中的函数,可以这样做:
[c light=”false” toolbar=”false”]
class D : public B {
public:
using B::f; // make every f from B available
double f(double d) { cout << “f(double): “; return d+1.3; }
// …
};
[/c]
那么结果就是:
f(int): 3 f(double): 3.6