简体   繁体   English

static_cast和dynamic_cast在特定场景中的不同行为

[英]different behavior of static_cast and dynamic_cast in a specific scenario

I don't figure out the real difference between static_cast and dynamic_cast in below scenario: 我在下面的场景中没有弄清楚static_cast和dynamic_cast之间的真正区别:

                                **///with static_cast///**
    class Foo{};
    class Bar: public Foo
    {
        public:
          void func()
          {
            return;
          }
    };

    int main(int argc, char** argv)
    {
        Foo* f = new Foo;
        Bar* b = static_cast<Bar*>(f);
        b->func();
        return 0;
    }

Output: 输出:

Successfully Build and Compiled! 成功构建和编译!

                                **///with dynamic_cast///**
    class Foo{};
    class Bar: public Foo
    {
        public:
          void func()
          {
            return;
          }
    };

    int main(int argc, char** argv)
    {
        Foo* f = new Foo;
        Bar* b = dynamic_cast<Bar*>(f);
        b->func();
        return 0;
    }

Output: 输出:

main.cpp: In function 'int main(int, char**)': main.cpp:26:34: error: cannot dynamic_cast 'f' (of type 'class Foo*') to type 'class Bar*' (source type is not polymorphic) Bar* b = dynamic_cast(f); main.cpp:在函数'int main(int,char **)'中:main.cpp:26:34:错误:不能用dynamic_cast'f'(类型'类Foo *')来键入'class Bar *'(源类型不是多态的)Bar * b = dynamic_cast(f);

I'd be appreciated if someone could help me understand this! 如果有人能帮助我理解这一点,我将不胜感激!

The hint is in the part 提示是在部分

(source type is not polymorphic) (源类型不是多态的)

It means, for dynamic_cast to work, it needs a polymorphic base class, ie have a virtual method 这意味着, dynamic_cast工作,它需要一个多态基类,即具有虚方法

class Foo {
public:
    virtual ~Foo() {}
};

Apart from that, it will not work, because f does not point to a Bar object. 除此之外,它不起作用,因为f不指向Bar对象。 dynamic_cast will return a nullptr in this case, which you must check 在这种情况下, dynamic_cast将返回nullptr,您必须检查它

Foo* f = new Foo;
Bar* b = dynamic_cast<Bar*>(f);
if (b != nullptr)
    b->func();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM