正常情况下我们可以通过使用相同的函数名而不同的参数或者返回值类型等因素来实现函数重载。但是在类的继承时这样的情况无法实现,因为类继承时,同名函数将会被掩盖,只要同名不管函数参数和返回值等类型是否相同都会被掩盖掉。如下进行简单的测试就可以很清楚的了解这一特性了。
1.正常情况下的函数重载:
- #include <cstdio>
- #include <cstring>
- #include <iostream>
-
- using namespace std;
-
- void bar(int c)
- {
- cout << "In function : void bar(int c) : c = " << c << endl;
- }
-
- void bar()
- {
- cout << "In function : void bar()" << endl;
- }
-
-
-
- int main()
- {
- int c = 2;
-
- bar(c);
- bar();
-
- return 0;
- }
以上代码就是一个最简单的重载代码。
2.在类的继承关系中的情况
- #include <cstdio>
- #include <cstring>
- #include <iostream>
-
- using namespace std;
-
- namespace iaccepted
- {
- class A
- {
- public:
- void bar(int c)
- {
- cout << "In function : void bar(int c) : c = " << c << endl;
- }
- };
-
- class B : public A
- {
- public:
- void bar()
- {
- cout << "In funcion : void bar()" << endl;
- }
- };
- }
-
- int main()
- {
- int c = 2;
-
- iaccepted::B b;
-
- b.bar();
- b.bar(c);
- return 0;
- }
这就是在类的继承关系中类似的情形。A中有一个bar(int)类型的函数,B中有一个bar()类型的函数,其实类B虽然继承类A中的内容,但是由于B中的bar与A中的函数同名,不管参数或者返回值是否相同,B中的bar都会掩盖掉A中的所有名为bar的函数(如果不止存在一个的话)。
结论:
类的继承关系中派生类中的函数会掩盖基类中的同名函数,而不管这些函数的参数和返回值类型等其他因素。