C++重载、覆盖与隐藏

来源:互联网 发布:恒创的域名服务器 编辑:程序博客网 时间:2024/05/21 22:39

一、重载

1、什么叫重载?如何实现重载?

将语义、功能相似的几个函数共用一个函数名,叫函数重载。函数重载使程序加简洁,减少命名重复,增强函数易用性;类的构造函数与类同名,且一个类可以有多种方式创建对象,此时需要重载机制。同名函数的参数列表不同,即参数类型、数目或顺序不同,编译器将根据参数产生不同的内部标识符,如void f(int x),void f(float x)对应产生_f_int,_f_float之类的标识符。

 

2、成员函数重载的特征

1)       函数作用域相同,即成员函数在同一个类中;

2)       函数名相同,参数列表不同;

3)       Virtual关键字可有可无;

4)       隐式类型转换导致重载函数产生二义性。

 

3、运算符重载

重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。

可重载的运算符列表:

+

-

*

/

%

^

&

|

~

!

,

=

<=

>=

++

--

<< 

>> 

==

!=

&&

||

+=

-=

/=

%=

^=

&=

|=

*=

<<=

>>=

[]

()

->

->*

new

new []

delete

delete []

不可重载运算符:

::

.*

.

?:

 

 

二、覆盖

成员函数的覆盖是指派生类函数覆盖基类函数,其特征为:

1)       函数名、函数参数列表必须完全一致;

2)       基类函数必须有virtual关键字;

3)       函数作用域为两个类(与重载不同)。

成员函数的重载与覆盖示例:

#include <iostream> using namespace std;class Base{public:    void f(int x){cout << " Base ::f(int) " <<x << endl;}    void f(float x){cout << " Base ::f(float) "<< x << endl;}    virtual void g(void){cout << " Base :: g(void) "<<endl;}private: }; class Derived :public Base{public:    virtual void g(void){cout << " Derived :: g(void) "<<endl;}}; int main(){    Derived d; Base *pb = &d; pb->f(42); pb->f(3.14f); pb->g();    return 0;}

输出结果为:


三、隐藏

隐藏是指派生类的函数屏蔽了基类中的同名函数,其特征有:

1)       派生类与基类中的成员函数名相同,参数列表不同,无论有无virtual关键字,基类函数被隐藏(与重载区分,重载同名成员函数位于同一个类中,隐藏同名函数分别位于派生类、基类两个类中);

2)       派生类与基类中的成员函数名相同,参数列表相同,基类没有virtual关键字,基类函数被隐藏(与覆盖区分,覆盖基类必须有virtual关键字,简而言之,当派生类与基类成员函数名相同、参数相同时有virtual关键字为覆盖,没有virtual关键字为隐藏)。

重载、覆盖、隐藏示例:

#include <iostream> using namespace std;class Base{public:    virtual void f(float x){cout << " Base ::f(float) "<< x << endl;}    void g(float x){cout << " Base ::g(float) "<< x << endl;}    void h(float x){cout << " Base ::h(float) "<< x << endl;}private: }; class Derived :public Base{public:    virtual void f(float x){cout << " Derived ::f(float) "<< x << endl;}    void g(int x){cout << " Derived ::g(int) "<<x << endl;}    void h(float x){cout << " Derived ::h(float ) "<<x << endl;}}; int main(){    Derived d; Base *pb = &d; Derived *pd = &d;  pb->f(3.14f);//基类被覆盖 pd->f(3.14f);  pb->g(3.14f);//基类被隐藏 pd->g(3.14f);  pb->h(3.14f);//基类被隐藏 pd->h(3.14f);       return 0;}

输出结果为:


参考文献:

1、《高质量C++/C编程指南》

2、http://www.runoob.com/cplusplus/cpp-overloading.html


0 0
原创粉丝点击