[英]What would be a use case for dynamic_cast of 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;
}
你建议的场景与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
}
}
它被称为交叉转换 ,当一个类从两个不同的类继承时使用它(不是相反,如你的问题所示)。
例如,给定以下类层次结构:
A B
\ /
C
如果你有一个指向C
对象的A
指针,那么你可以获得一个指向该C
对象的B
指针:
A* ap = new C;
B* bp = dynamic_cast<B*>(ap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.