本人在做qt的模型视图的代理时,当时需要继承重写几个函数,其中有个函数createEditor返回QWidget*,其实就是返回的函数内申请的控件的指针,因为Qt中的控件都是继承与QWidget,所以返回QWidget*很正常,还有一个函数是setEditorData(QWidget *editor, const QModelIndex &index) ,这个函数里面的editor就是刚刚createEditor返回的派生类转基类指针,我当时用的是static_cast转换editor为派生类,在运行的时候,一点击就崩溃。后来我才反应过来,static_cast转换的时候是静态的,编译时候可以并且成功,但是运行时候是不做检查的,一用就崩溃,需要改成dynamic_cast,然后程序就正常了。
这里就要说说static_cast和dynamic_cast了,
1 static_cast
延续了c语言的强制转换类型,double db = static_cast<double_type>(int_obj) , int it = static_cast<int_type>(enum_obj),基类指针转派生类指针,这样安全,派生类指针转基类指针,也可以,但是不安全。c++ primer也说了,还能把一个void*指针还原成特定指针,但是就是不安全,需要小心使用,使用者需要头脑清晰。比如:
ClassWindow * cw = static_cast<ClassBird * >(ptr);ClassWindow和ClassBird根本就没有关系,这样转换后运行指不定在什么地方用的时候崩溃。
ClassRoad * cr = new ClassRoad();
void * pt = static_cast<void * >(cr);
ClassHourse * ch = static_cast<ClassHourse * >(pt);//这样是不对的
ClassRoad * crr = static_cast<ClassRoad * >(pt);//这样才对
总而言之,static_cast在转换基本类型和父类指针转基类指针是安全的,其他的基类转父类特别不安全,所以c++推出了dynamic_cast
2 dynamic_cast
dynamic_cast就是用于相关联的基类指针和父类指针互相转换。在运行时会检查是否能转换成功,如果不能转换成功就返回0,所以我们在用dynamic_cast时都是
parent * p = dynamic_cast<parent*>(pchild);
if (p != nullptr){
}