简体   繁体   English

什么是dynamic_cast兄弟姐妹的用例?

[英]What would be a use case for dynamic_cast of siblings?

I'm reading Scott Meyers' More Effective C++ now. 我现在正在阅读Scott Meyers的“更有效的C ++”。 Edifying! 启发性! Item 2 mentions that dynamic_cast can be used not only for downcasts but also for sibling casts. 第2项提到dynamic_cast不仅可以用于downcast,也可以用于兄弟演员。 Could please anyone provide a (reasonably) non-contrived example of its usage for siblings? 可以请任何人为兄弟姐妹提供一个(合理的)非人为的例子吗? This silly test prints 0 as it should, but I can't imagine any application for such conversions. 这个愚蠢的测试打印0应该是,但我无法想象任何这种转换的应用程序。

#include <iostream>
using namespace std;

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

class D1 : public B {};

class D2 : public B {};

int main() {
    B* pb = new D1;
    D2* pd2 = dynamic_cast<D2*>(pb);
    cout << pd2 << endl;
}

The scenario you suggested doesn't match sidecast exactly, which is usually used for the casting between pointers/references of two classes, and the pointers/references are referring to an object of class which both derives from the two classes. 你建议的场景与sidecast完全不匹配,它通常用于两个类的指针/引用之间的转换,而指针/引用指的是类的对象,它们都派生自两个类。 Here's an example for it: 这是一个例子:

struct Readable {
    virtual void read() = 0;
};
struct Writable {
    virtual void write() = 0;
};

struct MyClass : Readable, Writable {
    void read() { std::cout << "read"; }
    void write() { std::cout << "write"; }
};
int main()
{
    MyClass m;
    Readable* pr = &m;

    // sidecast to Writable* through Readable*, which points to an object of MyClass in fact
    Writable* pw = dynamic_cast<Writable*>(pr); 
    if (pw) {
        pw->write(); // safe to call
    }
}

LIVE 生活

It is called cross-cast , and it is used when a class inherits from two different classes (not the other way around, as shown in your question). 它被称为交叉转换 ,当一个类从两个不同的类继承时使用它(不是相反,如你的问题所示)。

For example, given the following class-hierarchy: 例如,给定以下类层次结构:

A   B
 \ /
  C

If you have an A pointer to a C object, then you can get a B pointer to that C object: 如果你有一个指向C对象的A指针,那么你可以获得一个指向该C对象的B指针:

A* ap = new C;
B* bp = dynamic_cast<B*>(ap);

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

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