我正在阅读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;
}
答案 0 :(得分: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
}
}
答案 1 :(得分:2)
它被称为交叉投射,当一个类从两个不同的类继承时使用它(不是相反,如你的问题所示)。
例如,给定以下类层次结构:
var myInput = document.getElementById("input").value;
if (myInput === '0') {
document.getElementById("input").style.display = 'none';
}
如果你有一个指向A B
\ /
C
对象的A
指针,那么你可以得到一个指向该C
对象的B
指针:
C