dynamic_cast的文章看了很多,大多是说,“可以这样做,不可以这样做”,今天花了半天时间,仔细学了一下,收获颇丰。整理了一下,比较乱,很多东西依然模棱两可,有机会看了《深入理解C++对象模型》之后再好好补充。
dynamic_cast
主要用来执行“安全向下转型”,也就是用来决定某对象是否归属继承体系中的某个类型。
dynamic_cast
是用来检查两者是否有继承关系。因此该运算符实际上只接受基于类对象的指针和引用的类转换。
来看cppreference上面的说法:
dynamic_cast < new_type > ( expression )
1) If the type of expression is exactly new_type or a less cv-qualified version of new_type, the result is the value of expression, with type new_type. (In other words, dynamic_cast can be used to add constness. An implicit cast and static_cast can perform this conversion as well.)
class Fuck
{
public:
int a;
Fuck():a(10){}
~Fuck(){}
};
int main() {
Fuck f;
const Fuck *pb = dynamic_cast< const Fuck *>(&f);
//const Fuck b = dynamic_cast< const Fuck >(f);//error:必须是指向完整类类型指针或者void*
const Fuck cf;
//Fuck *pc=dynamic_cast<Fuck*>(&cf);//error:这件事应该交给const_cast
cout << pb->a << endl;//输出10
system("pause");
}
类型一致没什么好说的,这跟static_cast行为一致。并且可以对less-cv的type做const转型,用原文的话来说:dynamic_cast can be used to add constness
2) If the value of expression is the null pointer value, the result is the null pointer value of type new_type.
空指针的转型将得到新类型的空指针。
3) If new_type is a pointer or reference to Base, and the type of expression is a pointer