C++深度解析 多态的概念和意义 --- virtual,虚函数,静态联编,动态联编

C++深度解析 多态的概念和意义 --- virtual,虚函数,静态联编,动态联编

多态

通过使用virtual关键字对多态进行支持

示例程序:

#include <iostream>
#include <string>
 
using namespace std;
 
class Parent
{
public:
    //print()函数被继承会被重写,多态的行为
    virtual void print()
    {
        cout << "I'm Parent." << endl;
    }
};
 
class Child : public Parent
{
public:
    //虚函数
    void print()
    {
        cout << "I'm Child." << endl;
    }
};
 
void how_to_print(Parent* p)
{
    p->print(); //展现多态的行为
}
 
int main()
{
    Parent p;
    Child c;
    
    how_to_print(&p);   // Expected to print:I'm Parent
    how_to_print(&c);   // Expected to print:I'm Child
    
    return 0;
}

结果如下:

多态的意义:

在程序运行过程中展现出动态的特性

函数重写必须多态实现,否则没有意义

多态是面向对象组件化程序设计的基础特性

静态联编:

在程序的编译期间就能确定具体的函数调用,如:函数重载

动态联编:

在程序实际运行后才能确定具体的函数调用,如:函数重写

示例程序:

#include <iostream>
#include <string>

using namespace std;

class Parent
{
public:
    //虚函数
    virtual void func()
    {
        cout << "void func()" << endl;
    }
    //虚函数
    virtual void func(int i)
    {
        cout << "void func(int i) : " << i << endl;
    }
    //虚函数
    virtual void func(int i, int j)
    {
        cout << "void func(int i, int j) : " << "(" << i << ", " << j << ")" << endl; 
    }
};

class Child : public Parent
{
public:
    //重写父类的函数,虚函数
    void func(int i, int j)
    {
        cout << "void func(int i, int j):" << i + j << endl;    
    }
    //在Child类里面的两个func()函数,是函数重载
    void func(int i, int j, int k)
    {
        cout << "void func(int i, int j, int k):" << i + j + k << endl;
    }
};

//全局函数
void run(Parent* p)
{
    //同一行语句展现出不同的调用结果
    p->func(1, 2);  //展现多台的特性  //动态联编
}

int main()
{
    Parent p;
    
    p.func();       //静态联编
    p.func(1);      //静态联编
    p.func(1, 2);   //静态联编
    
    cout << endl;
    
    Child c;
    
    c.func(1, 2);   //静态联编
    
    cout << endl;
    
    run(&p);        //动态联编
    run(&c);        //动态联编
    
    return 0;
}

结果如下:

猜你喜欢

转载自blog.csdn.net/xiaodingqq/article/details/85985925