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

标签 c++ oop inheritance dynamic-cast static-cast

在下面的场景中,我没有弄清楚 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);

如果有人能帮助我理解这一点,我将不胜感激!

最佳答案

提示在部分

(source type is not polymorphic)

这意味着,要使 dynamic_cast 工作,它需要一个多态基类,即有一个虚方法

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

除此之外,它不会工作,因为 f 不指向 Bar 对象。 dynamic_cast 在这种情况下将返回一个 nullptr,您必须检查它

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

关于c++ - static_cast 和 dynamic_cast 在特定场景中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48638365/

相关文章:

c++ - __REQUIRED_RPCNDR_H_VERSION__

c++ - MinGW/G++/g95 链接错误 - libf95 未定义对 `MAIN_' 的引用

c++ - 为什么模板创建第二个参数的本地拷贝?

javascript - 添加几个类实例到 'container'类属性对象

oop - 在类(class)等级制度中经常下垂是永远邪恶的吗?

wpf - FrameworkElement 的 DataContext 属性不会沿元素树继承

C++从已实现的虚拟类调用非虚拟方法

objective-c - 声明 Objective C 对象时哪个更有效

具有继承类型问题的 Java Builder

c++ - C++中的虚函数问题