實際上,這些演員陣容是代碼中不確定事件的明顯標記,因此在完美的世界中,您不應該使用它們。
但在某些情況下,他們是正確的工具。
對於的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