從執行期得知class名稱

有時我們想知道在執行期時,我們使用的到底是哪個類別,可以利用typeid()來達成:

#include "stdafx.h"
#include <iostream>
#include <typeinfo>    // typeid Header

class CBase
{
public:
    CBase() {}
    ~CBase() {}

    virtual void foo() 
    {
        std::cout << "CBase!!!!!\n";
    }

private:
    CBase(const CBase& rhs) {}
    CBase& operator= (const CBase& rhs) {}
};

class CDerived : public CBase
{
public:
    CDerived() {}
    ~CDerived() {}

    void foo() 
    {
        std::cout << "CDerived!!!!!\n";
    }

private:
    CDerived(const CDerived& rhs) {}
    CDerived& operator= (const CDerived& rhs) {}
};

int _tmain(int argc, _TCHAR* argv[])
{
    CBase *A = new CDerived;

    std::cout << typeid(*A).name() << std::endl;
    std::cout << typeid(A).name() << std::endl;
    system("pause");
    return 0;
}
另外,一個類別裡若是有任一函數加上virtual,那該類別會在執行期時才會決定要調用哪一個類別函數,例如上面的:
CBase *A = new CDerived;
編譯時只會知道說A是宣告成CBase指標,雖然說new成CDerived,但因為CDerived繼承CBase,所以是沒問題的,所以此時若使用A->foo(),它是先指向CBase::foo(),等到執行期時,因foo()為virtual函數,此時就會去連結到CDerived::foo()(其實這牽扯到vtable的問題,不過這要說一堆東西,我懶!)。

以上其實用typeid來觀察就會很清楚了。

0 意見:

張貼留言