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

sig*_*gil 7 c++ inheritance dynamic-cast siblings

我现在正在阅读Scott Meyers的"更有效的C++".启发性!第2项提到dynamic_cast不仅可以用于downcast,也可以用于兄弟演员.可以请任何人为兄弟姐妹提供一个(合理的)非人为的例子吗?这个愚蠢的测试打印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;
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

你建议的场景与sidecast完全不匹配,它通常用于两个类的指针/引用之间的转换,而指针/引用指的是类的对象,它们都派生自两个类.这是一个例子:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

生活