我正在学习C++。 我想尝试downcast一个接口类;尽管我已经学会了不好的编程设计可能会导致铸造失败。我可以使用static_cast来强制转型吗?
一些网站说:“使用dynamic_cast检查向下铸造的有效性”。但是,就我而言,我不需要检查有效性,因为我可以保证它是从基类向派生类的向下转换。我在下面的示例代码中尝试了dynamic_cast和static_cast。他们运作良好。
当我可以保证它是一个有效的向下转换时,我可以使用static_cast吗?
示例代码:
struct Parent_Interface {
virtual ~Parent_Interface() {};
virtual void print(void) = 0;
};
struct Child : public Parent_Interface {
virtual ~Child() {};
void print(void) override {
std::cout << "Child::print()." << std::endl;
}
};
void StaticDownCastToChild(Parent_Interface& parent_interface) {
auto& child0 = static_cast<Child&>(parent_interface);
std::cout << "StaticDownCastToChild : ";
child0.print();
}
void DynamicDownCastToChild(Parent_Interface& parent_interface) {
auto& child0 = dynamic_cast<Child&>(parent_interface);
std::cout << "DynamicDownCastToChild : ";
child0.print();
}
void test_static_cast_down_cast(void) {
Child c;
StaticDownCastToChild(c);
DynamicDownCastToChild(c);
}
执行test_static_cast_down_cast的输出()。
StaticDownCastToChild : Child::print().
DynamicDownCastToChild : Child::print().
使用'static_cast'是推荐的方式。只是关于*任何*演员。 –
CRTP就是一个例子。 – chris