C++中不能在派生类中对父类函数进行重载

查看如下代码段:

[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

By Lu Jun

80后男,就职于软件行业。习于F*** GFW。人生48%时间陪同电子设备和互联网,美剧迷,高清视频狂热者,游戏菜鸟,长期谷粉,临时果粉,略知摄影。

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.