C++ 多态的简单示例

来源:互联网 发布:西门子s7200仿真软件 编辑:程序博客网 时间:2024/06/04 08:11
面向对象的三大特性是封装,继承和多态,本文主要介绍C++里的多态特性
在编译器把函数或模板连接生产执行代码的过程中,有两种联编方式,一种是静态联编,另外一种是动态联编,
静态联编是在编译阶段就把函数连接起来,就可以确定调用哪个函数或者模板,而动态联编是指在程序运行时才能确定函数和实现的连接,才能确定调用哪个函数

根据联编的方式我可以把多态(函数多种形态)分成两种,静态多态和动态多态,网上有些资料有四种,多出了宏多态和函数多态,但我个人认为这两种应该属于静态多态

动态多态
主要通过继承和虚函数实现,父类指针或者引用能够指向子类对象,调用子类的虚函数,所有在编译时是无法确定调用哪个虚函数,每个子类都维护着一张虚函数表,

程序执行时查询虚函数表来确定调用哪个虚函数;

#include <iostream>    using namespace std;    class Base    {       public:           virtual void Print() = 0;           virtual ~Base(){}    };    class child_1 : public Base    {       public:        void Print()        {            cout << "child_1 Print function" << endl;        }        ~child_1()        {            cout << "child_1 destructor function" << endl;        }    };    class child_2: public Base    {        public:            void Print()            {                cout << "child_2 Print function" << endl;            }            ~child_2()            {                cout << "child_2 destructor function" << endl;            }    };    int main()    {        Base *p = new child_1; //父类指针指向子类对象        p->Print();        delete p;  //记住释放,否则内存泄露        p = new child_2;        p->Print();        delete p;        p = NULL;        return 0;    }


存在这样的多态特性,所有最好是把类的析构函数定义成virtual类型,否则在释放时无法调用析构函数



静态多态
使用的是静态联编方式,在编译时函数和函数的实现就关联在一起,主要是通过重载和模板实现,在宏多态中,是通过定义变量,编译时直接把变量替换,实现宏多态.

#include <iostream>    using namespace std;    //宏多态;a,b可以不同类型    #define  sum(a,b)  ((a) + (b))    class Base    {        public:            void Print() //不需要定义为虚函数            {               cout << "base Print() functions" << endl;            }            void Print(int val) //重载,根据参数列表不同实现函数多态            {                cout << "base Print(int) functions" << endl;            }    };    class child : public Base    {        public:            void Print() //不需要定义为虚函数            {                cout << "child Print() functions" << endl;            }            void Print(int val) //重载,根据参数列表不同实现函数多态            {                cout << "child Print(int) functions" << endl;            }                };    template<typename T>    void func(T &p)    {       p.Print();       p.Print(1);    }    int main()    {        Base base ;        child ch;        int a = 23, b = 19;        double fa = 13.32, fb = 29.36;        func(base);        func(ch);        cout << sum(a,b) << endl;        cout << sum(fa,fb) << endl;        return 0;    }




原创粉丝点击