c++ 中的动态铸造到底是什么?

发布于 2024-08-11 23:44:30 字数 73 浏览 6 评论 0原文

谁能告诉我动态转换在c++中到底意味着什么。 我们到底可以在哪里使用这种动态铸造呢? 这是在面试时问我的,我对这个问题一片空白:)。

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:).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

前事休说 2024-08-18 23:44:30

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。

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

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.

风筝在阴天搁浅。 2024-08-18 23:44:30

首先尝试使用搜索
旧答案

Try to use the search first
old answer

〆一缕阳光ご 2024-08-18 23:44:30

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

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

Dynamic casting is 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文