不能动态投射侧身 [英] Cannot dynamic_cast sideways

查看:68
本文介绍了不能动态投射侧身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了从派生类到派生类的横向转换,并发现了我的知识空白.我一直生活在一个可以做到这一点的世界 - 直到现在.相反,会抛出 std::bad_cast.这是怎么回事?

I stumbled upon casting sideways from derived to derived class and discovered a gap in my knowledge. I had been living in a world where this is possible - until now. Instead, std::bad_cast is thrown. What's going on here?

#include <iostream>

class Base
{
protected:
    int x_;

public:
    Base(int x) : x_(x) {}
    virtual ~Base() = default;
    int x() const { return x_; }
    virtual void setX(int x) = 0;
};

class Editable : public Base // class implements setters
{
public:
    Editable(int x) : Base(x) {}
    void setX(int x) { x_ = x; }
};

class ReadOnly : public Base // class implements empty setters
{
public:
    ReadOnly(int x) : Base(x) {}
    void setX(int x) {}
};

int main()
{
    Editable editable(4);
    ReadOnly &readOnly = dynamic_cast<ReadOnly&>(editable); // std::bad_cast
}

推荐答案

这就是人们说 dynamic_cast 可以侧向投射的意思:

This is what is meant when people say that dynamic_cast can cast sideways:

struct A { virtual ~A() = default; };
struct B { virtual ~B() = default; };
struct D : A, B {};

B* pb = new D();
A* pa = dynamic_cast<A*>(pb); // OK

即,它允许您将 B* 转换为 A* 如果指针指向的是从 A 派生的内容和 B.要使转换成功,仍然必须有一个 A 子对象供指针指向(或绑定到的引用,如果您要转换为引用类型).

i.e., it allows you to cast a B* to a A* if the pointer is pointing to something that's derived from both A and B. For the cast to succeed, there still must be an A subobject for the pointer to point to (or the reference to bind to, if you are casting to a reference type).

就您而言,e 是一个 Editable.那里的任何地方都没有 ReadOnly 子对象.所以演员表失败了.

In your case, e is an Editable. There's no ReadOnly subobject anywhere in there. So the cast fails.

这篇关于不能动态投射侧身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆