我正在阅读 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
}
}
关于c++ - sibling 的 dynamic_cast 的用例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406567/