cast not needing to perform a run
This question already has an answer here:
class Base {
public:
virtual ~Base() {}
// ...
};
class Derived : public Base {
// ...
};
"Typical use":
void foo(Derived*);
void f(Base* pb)
{
if (Derived* pd = dynamic_cast<Derived*>(pb)) {
foo(pd);
}
}
"Above quote":
void bar(Base*);
void f(Derived* pd)
{
Base* pb = dynamic_cast<Base*>(pd); // the dynamic_cast is useless here
// because a Derived IS-A Base, always
bar(pb); // Note: could as well call directly bar(pd); (implicit conversion)
}
dynamic_cast
is mostly used for downcast and cross-cast. The gotcha mentions upcast.
Having structs B1, B2, D:B1, B2:
上一篇: 重新解释的目的是什么?
下一篇: 不需要执行运行