C++多态性

来源:互联网 发布:零基础编程入门 编辑:程序博客网 时间:2024/06/07 13:49

多态性

  指相同对象收到不同消息或不同对象收到相同消息时产生不同的实现动作。C++支持两种多态性:编译时多态性,运行时多态性。  a、编译时多态性:通过重载函数实现  b、运行时多态性:通过虚函数实现。 

多态存在的三个条件:

  • 必须存在继承关系;
  • 继承关系中必须有同名的虚函数,并且它们是覆盖关系(重载不行);
  • 存在基类的指针,通过该指针调用虚函数。

overload、override、hide的区别:

1).重载:成员函数具有以下的特征时发生“重载”

A.相同的范围(同一个类中)

B.函数的名字相同

C.参数类型不同(不能进行隐式类型转换)

D.Virtual关键字可有可无

2).覆盖(也叫“继承”):指派生类函数覆盖基类函数,特征是:

A.不同的范围(分别位于基类与派生类中)

B.函数名字相同

C.参数相同

D.基类函数必须有virtual关键字

3).隐藏:是指派生类的函数屏蔽了与其同名的基类函数,规则如下:

A.如果派生类的函数与基类的函数同名,但是参数不同,此时不论有无virtual关键字,基类的函数都将被隐藏,注意别与重载混淆)

B.如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字,此时基类的函数被隐藏(注意别与覆盖混淆)

/*****************************************> File Name : polymorphism.cpp> Description : C++多态    g++ -g -o polymorphism polymorphism.cpp    小结:1、有virtual才可能发生多态现象        2、不发生多态(无virtual)调用就按原类型调用> Author : linden> Date : 2016-02-22*******************************************/#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;        }};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(int argc, char *argv[]){    Derived d;    Base *pb = &d;    Derived *pd = &d;    // Good : behavior depends solely on type of the object    pb->f(3.14f);   // Derived::f(float) 3.14    pd->f(3.14f);   // Derived::f(float) 3.14    // Bad : behavior depends on type of the pointer    pb->g(3.14f);   // Base::g(float)  3.14    pd->g(3.14f);   // Derived::g(int) 3     // Bad : behavior depends on type of the pointer    pb->h(3.14f);   // Base::h(float) 3.14    pd->h(3.14f);   // Derived::h(float) 3.14    return 0;}

参考链接:

  • http://www.cppblog.com/zmllegtui/archive/2008/10/28/65386.html
0 0
原创粉丝点击