1. 程式人生 > >C++深度解析 多型的概念和意義 --- virtual,虛擬函式,靜態聯編,動態聯編

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;
}

結果如下: