c++ - sibling 的 dynamic_cast 的用例是什么?

标签 c++ inheritance siblings dynamic-cast

我正在阅读 Scott Meyers 的《更有效的 C++》。教化! Item 2 提到 dynamic_cast 不仅可以用于向下转换,还可以用于兄弟转换。任何人都可以提供一个(合理的)非人为的例子来说明它对 sibling 的用法吗?这个愚蠢的测试按它应该打印 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;
}

最佳答案

您建议的方案与 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
    }
}

LIVE

关于c++ - sibling 的 dynamic_cast 的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406567/

相关文章:

java - 在所有 Activity android中导入常用功能

c++ - `select`如何同时处理多个事件?

c++ - 未初始化 vector 中的元素值是多少?

c++ - 为什么在使用 QList 时 std::sort 会崩溃?

java - 继承:子类中方法的可访问性较弱

c# - 继承自 System.Timers.ElapsedEventArgs 使单元测试更容易

jquery - Jquery如何获取 parent sibling 的内容

jquery removeClass 仅当同一组(具有相同类?)的所有复选框均未选中时

javascript - 如何使用 jQuery 遍历 sibling ?

c++ - 使用 boost::random 并获得相同的数字序列