繁体   English   中英

为什么 static_cast 有效但 dynamic_cast 失败?

[英]Why static_cast works but dynamic_cast fails?

假设我有一个基础 class 和 2 个从中派生的类。 所有派生类都有自己的逻辑,它们之间不兼容。 测试应用如下:

#include <iostream>
#include <vector>
    
class Base
{
public:
    Base(int x) { m_x = x; }
    virtual int getResult() { return m_x; }
protected:
    int m_x;
};


class DerivedA : public Base
{
public:
    DerivedA(int x) : Base(x) {}
    int getResult() override { return m_x * 2; }
};

class DerivedB : public Base
{
public:
    DerivedB(int x) : Base(x) {}
    int getResult() override { return m_x * m_x; }
};


int main()
{
    std::vector<Base *> objects;
    objects.push_back(new DerivedA(1));
    objects.push_back(new DerivedB(2));
    objects.push_back(new DerivedA(3));
    objects.push_back(new DerivedB(4));

    for(Base *object: objects)
    {
        DerivedA *obj = static_cast<DerivedA *>(object);
        if(obj != nullptr)
        {
            std::cout << obj->getResult() << std::endl;
        }
    }

    return 0;
}

我希望只得到 2 个结果,即只有DerivedA类型的实例可以转换为DerivedA但不能转换为DerivedB 但令我惊讶的是,事实并非如此。 static_castDerivedB转换为DerivedA没有问题。 为什么会这样? 我可以理解,如果我会投到Base但不是那样。 同时, dynamic_cast按预期工作, DerivedBDerivedA失败。

将作为DerivedB*static_cast结果的指针取消引用到DerivedA*的行为是undefined 这是一个严格的混叠违规。

暂无
暂无

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

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