重载,覆盖与隐藏

成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;

(4)virtual 关键字可有可无。

隐藏与重载的区别:

(1)不同的范围
(2)函数名相同
(3)参数不同
(4)virtual 关键字可有可无

 

覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;

(4)基类函数必须有virtual 关键字。

隐藏与覆盖的区别:

(1)不同的范围

(2)函数名相同

(3)参数相同

(4)基类没有virtual关键字

 1 #include <stdio.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 class Base
 6 {
 7 public:
 8     virtual void f(float x){ cout << "Base::f(float) " << x << endl; }
 9     void g(float x){ cout << "Base::g(float) " << x << endl; }
10     void h(float x){ cout << "Base::h(float) " << x << endl; }
11 };
12 
13 class Derived : public Base
14 {
15 public:
16     virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }
17     void g(int x){ cout << "Derived::g(int) " << x << endl; }
18     void h(float x){ cout << "Derived::h(float) " << x << endl; }
19 };
20 
21 int main(void)
22 {
23         Derived d;
24         Base *pb = &d;
25         Derived *pd = &d;
26         // Good : behavior depends solely on type of the object
27         pb->f(3.14f); // Derived::f(float) 3.14
28         pd->f(3.14f); // Derived::f(float) 3.14
29         // Bad : behavior depends on type of the pointer
30         pb->g(3.14f); // Base::g(float) 3.14
31         pd->g(3.14f); // Derived::g(int) 3 (surprise!)
32         // Bad : behavior depends on type of the pointer
33         pb->h(3.14f); // Base::h(float) 3.14 (surprise!)
34         pd->h(3.14f); // Derived::h(float) 3.14
35 
36         return 0;
37 }
View Code

摆脱隐藏
隐藏规则引起了不少麻烦。示例程序中,语句pd->f(10)的本意是想调用函数Base::f(int),但是Base::f(int)不幸被Derived::f(char *)隐藏了。由于数字10不能被隐式地转化为字符串,所以在编译时出错。

 1 class Base
 2 {
 3 public:
 4     void f(int x);
 5 };
 6 class Derived : public Base
 7 {
 8 public:
 9     void f(char *str);
10 };
11 void Test(void)
12 {
13     Derived *pd = new Derived;
14     pd->f(10); // error
15 }
View Code

从示例 看来,隐藏规则似乎很愚蠢。但是隐藏规则至少有两个存在的理由:

写语句pd->f(10)的人可能真的想调用Derived::f(char *)函数,只是他误将参数写错了。有了隐藏规则,编译器就可以明确指出错误,这未必不是好事。否则,编译器会静悄悄地将错就错,程序员将很难发现这个错误,流下祸根。

假如类Derived 有多个基类(多重继承),有时搞不清楚哪些基类定义了函数f。如果没有隐藏规则,那么pd->f(10)可能会调用一个出乎意料的基类函数f。尽管隐藏规则看起来不怎么有道理,但它的确能消灭这些意外。
示例中,如果语句pd->f(10)一定要调用函数Base::f(int),那么将类Derived 修改为如下即可。

1 class Derived : public Base
2 {
3 public:
4 void f(char *str);
5 void f(int x) { Base::f(x); }
6 };
View Code

转自:http://blog.csdn.net/zzj1881/article/details/7928346

posted @ 2013-07-05 08:31  simon1024  阅读(147)  评论(0)    收藏  举报