2009-11-23 66 views
0

任何人都可以告訴什麼是動態鑄造手段在c + +。 我們到底在哪裏可以使用這種動態投射? 這是在採訪中問我的,我對這個問題空着:)。究竟是什麼動態鑄造在c + +

+0

dup http://stackoverflow.com/questions/28002/regular-cast-vs-staticcast-vs-dynamiccast – Macke 2009-11-23 11:22:56

回答

2

嘗試使用搜索第一 old answer

+1

好的指針,雖然跳過接受的答案,並鑽研到第二個(通過litb)這是正確的...不像第一個:/ – 2009-11-23 08:37:32

+0

@Mathieu:時間確定了,litb'現在是第一個答案。無論如何感謝提示。 – philant 2010-09-27 10:18:40

0

Dynamic casting正在運行時安全地發現對象實例的類型。

這是通過編譯器生成引用表來實現的,引用表可能相當大。出於這個原因,如果程序員知道他們沒有使用該功能,那麼在編譯過程中通常會禁用它。

7

dynamic_cast的是鑄造方法在運行時發現對象的類。

class Base 
{ 
    public: 
    virtual bool func1(); 
}; 


class Derived1 : Base 
{ 
    public: 
    virtual bool func1(); 

    virtual bool funcDer1(); 
}; 



class Derived2 : Base 
{ 
    public: 
    virtual bool func1(); 
    virtual bool funcDer2(); 
}; 

Base* pDer1 = new Derived1; 
Base* pDer2 = new Derived2; 


Derived2* pDerCasted = dynamic_cast<Derived2*>(pDer2); 
if(pDerCasted) 
{ 
    pDerCasted->funcDer2(); 
} 


-> We cannot call funcDer2 with pDer2 as it points to Base class 
-> dynamic_cast converts the object to Derived2 footprint 
-> in case it fails to do so, it returns NULL .(throws bad_cast in case of reference) 

注意:通常情況下,Dynamic_cast應避免仔細的OO設計。

+0

我想你的意思是Derived2 * pDerCasted ..? – lorenzog 2009-11-23 08:39:09

+0

是的,派生的2。我已更新。 – 2009-11-23 08:41:37