【发布时间】:2012-09-25 17:40:33
【问题描述】:
请注意以下代码。据我所知,dynamic_cast 比 static_cast 慢。因为它在运行时评估类型。 我的疑问是,如果我们将 static_cast 与 typeid() 一起使用如下,它是否需要与动态转换相同的时间? 会比 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,感谢您的建议,我只想知道它们之间的时间差异。我会检查任何预定义的函数
标签: c++ dynamic-cast static-cast