C++中多態總結

一. 多態的概念

同一事物,在不同場景下的多種形態

例如:“*”在不同場景下的形態

 int* p=&a;//指針
 *p;//解引用
 a*b;//乘號

二.多態的分類

1.靜態多態:編譯器在編譯期間完成的,編譯器根據函數實參的類型(可能會進行隱式類型轉換),可推斷出要調用那個函數,如果有對應的函數就調用該函數,否則出現編譯錯誤。

int Add(int a,int b)
{
   return a+b;
}

float Add(int a,int b)
   return a+b;
}

int main()
{
   cout<<Add(10,20)<<end1;
   cout<<Add(3.14f,5.6f)<<end1;
   return 0;
}

2.動態多態:在程序執行期間(非編譯期)判斷所引用對象的實際類型,根據其實際類型調用相應的方法。

class WashRoom

{

public: void GoToManWashRoom()

{

    cout << "Man-->Please Left" << endl;

}

        void GoToWomanWashRoom()

        {

            cout << "Woman-->Please Right" << endl;

        }

};

class Person

{

public: virtual void GoToWashRoom(CWashRoom & _washRoom) = 0;

};

class Man :public Person

{

public: virtual void GoToWashRoom(WashRoom & washRoom)

{

    washRoom.GoToManWashRoom();

}

};

};

class Woman :public Person

{

public:

    virtual void GoToWashRoom(WashRoom & washRoom)

    {

        washRoom.GoToWomanWashRoom();

    }

};

void FunTest()

{

    WashRoom washRoom;

    for (int iIdx = 1; iIdx <= 10; ++iIdx)

    {

        Person* pPerson;

        int iPerson = rand() % iIdx;

        if (iPerson & 0x01)

            pPerson = new Man;

        else

            pPerson = new Woman;

        pPerson->GoToWashRoom(washRoom);

        delete pPerson;

        pPerson = NULL;
                Sleep(1000);

    }

三. 動態多態的實現條件

1.基類中必須有虛函數;

class Base
{
public:
    virtual void FunTest1(int _iTest){ cout << "Base::FunTest1()" << endl; }
    void FunTest2(int _iTest){ cout << "Base::FunTest2()" << endl; }
    virtual void FunTest3(int _iTest1){ cout << "Base::FunTest3()" << endl; }
    virtual void FunTest4(int _iTest){ cout << "Base::FunTest4()" << endl; }
};
class Derived :public Base
{
public:
    virtual void FunTest1(int _iTest){ cout << "Derived::FunTest1()" << endl; }
    virtual void FunTest2(int _iTest){ cout << "Derived::FunTest2()" << endl; }
    void FunTest3(int _iTest1){ cout << "Derived::FunTest3()" << endl; }
    virtual void FunTest4(int _iTest1, int _iTest2)
        virtual void FunTest4(int _iTest1, int _iTest2)
    {
        cout << "Derived::FunTest4()" << endl;
    }
};
int main()
{
    Base* pBase = new Derived;
    pBase->FunTest1(0);
    pBase->FunTest2(0);
    pBase->FunTest3(0);
    pBase->FunTest4(0);
    pBase->FunTest4(0, 0);
    return 0;
}

2.通過基類類型的引用或者指針調用虛函數;

四.多態的實現原理

a、編譯時多態性(靜態多態):通過重載函數實現

b、運行時多態性(動態多態):通過虛函數實現。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章