0

谁能告诉 C++ 中的动态转换到底是什么意思。我们究竟可以在哪里使用这种动态转换?这是在面试中问我的,我对这个问题一无所知:)。

4

3 回答 3

9

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)

注意:通常情况下,应通过仔细的 OO 设计来避免 Dynamic_cast。

于 2009-11-23T08:31:53.417 回答
2

尝试使用搜索第一 个旧答案

于 2009-11-23T08:25:23.563 回答
0

动态转换是在运行时安全地发现对象实例的类型。

这是通过编译器生成参考表来实现的,参考表可能相当大。出于这个原因,如果程序员知道他们不使用该功能,它通常在编译期间被禁用。

于 2009-11-23T08:23:37.750 回答