請注意以下代碼。據我所知,dynamic_cast比static_cast慢。因爲它在運行時評估類型。 我的疑問是,如果我們使用typeid()的static_cast作爲下面,它將需要相同的時間作爲動態演員? 它會比dynamic_cast更快嗎?static_cast和RTTI vs dynamic_cast
class Shape
{
public:
virtual ~Shape(){}
};
class Circle : public Shape{ };
class Square : public Shape{ };
靜態鑄造用RTTI:
Circle c;
Shape* s = &c; // Upcast: normal and OK
// More explicit but unnecessary:
s = static_cast<Shape*>(&c);
// (Since upcasting is such a safe and common
// operation, the cast becomes cluttering)
Circle* cp = 0;
Square* sp = 0;
// Static Navigation of class hierarchies
// requires extra type information:
if(typeid(s) == typeid(cp)) // C++ RTTI
cp = static_cast<Circle*>(s);
if(typeid(s) == typeid(sp))
sp = static_cast<Square*>(s);
if(cp != 0)
cout << "It's a circle!" << endl;
if(sp != 0)
cout << "It's a square!" << endl;
動態轉換:
Circle c;
Shape* s = &c; // Upcast: normal and OK
s = &c;
Circle* cp = 0;
Square* sp = 0;
cp = dynamic_cast<Circle*>(s);
if(cp != 0)
cout << "It's a circle!" << endl;
sp = dynamic_cast<Square*>(s);
if(sp != 0)
cout << "It's a square!" << endl;
這隻有在你引用指向對象的指針時纔有效。只有這樣''typeid'才能與動態類型的對象一起工作,而不是隻給你'Circle *'和'Shape *'回來。 –
嗨Pileborg,感謝您的建議,我只是想知道他們之間的時差。我會檢查任何預定義的功能 – ranganath111
嘗試一下並回報。 –