什么是 C++ 中的动态转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1781763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:09:08  来源:igfitidea点击:

what exactly is dynamic casting in c++

c++dynamic-cast

提问by Vijay

can anyone tell what exactly is dynamic casting means in c++. where exactly can we use this dynamic casting? this was asked to me in the interview and i went blank for this question:).

谁能说出 C++ 中动态转换的确切含义。我们究竟可以在哪里使用这种动态转换?这是在面试中问我的,我对这个问题空白了:)。

回答by aJ.

dynamic_cast is casting method to find out the object's class at runtime.

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)

Note: Usually, Dynamic_cast should be avoided with careful OO design.

注意:通常,在谨慎的 OO 设计中应该避免使用 Dynamic_cast。

回答by ziggystar

Try to use the search first old answer

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

回答by Will

Dynamic castingis safely discovering the type of an object instance at runtime.

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

This is achieved by the compiler generating reference tables, which can be potentially rather large. For this reason, it is often disabled during compilation if the programmer knows that they do not use the feature.

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