实际上,这些演员阵容是代码中不确定事件的明显标记,因此在完美的世界中,您不应该使用它们。
但在某些情况下,他们是正确的工具。
对于的static_cast,基本上有两种情况:
1.原始转换。
当你确实需要一些整数在一个涉及浮点的演算中被处理。
float ratio = static_cast<float>(pixel_pos.x)/static_cast<float>(pixel_pos.y); // x and y are integers because pixel positions are absolute, but we need to get a floating point value here
2.你有一些外部API的对象,你想要得到的特定的子类。
Thing* thing = factory.create("shoe"); // Even if I don't have it's real type, I know it's a shoe!
Shoe* shoe = static_cast<Shoe*>(thing); // I need to use Shoe interface so lets cast it.
如果你设计了系统,也许你可以做得更好,以避免演员。但是如果你没有,并且你使用的API提供了基本类型作为你使用它的一种方式,那么你没有别的选择,只能投射。
static_cast也很有用,因为它可以让你在编译时假设一些东西,所以你应该首先使用它,因为它需要你确定你在做什么。
3。你不知道什么是对象的真实类型。
但是,在运行时需要知道实际类型时有一种特殊情况,因为在另一次无法让您知道它。典型的情况是,当你从外部系统接收某种物体并没有对现实类型的对象
void on_something_happen(const Event& event) // callback triggered when an event occured in the library system this callback is plugged in
{
// here I want to manage two cases
ThingEvent* thing_event = dynamic_cast<ThingEvent*>(&event);
if(thing_event)
{
// do my thing
}
else
{
// ok this event HAVE TO be a FooEvent, otherwise this should crash
FooEvent& foo_event = dynamic_cast<FooEvent&>(event);
// do my thing
}
}
对于一个考虑周全的设计,如果不是0,则使用类型转换的次数最少。 – 2012-03-31 12:19:53
'b'将表现为'Derive *',因为如果您将一个虚拟成员函数添加到'Base'并覆盖它在'Derive'中后者会在你执行'b-> f()'时被调用。 'd'的定义会给你一个编译时错误。 – 2012-03-31 12:40:08
@NicolaMusatti,为什么编译错误? – Alcott 2012-03-31 12:45:18