1、static_cast:可以实现C++中内置基本数据类型之间的相互转换。
int c=static_cast<int>(7.987);如果涉及到类的话,static_cast只能在有相互联系的类型中进行相互转换,不一定包含虚函数。
class A {}; class B:public A {}; class C {}; int main() { A* a=new A; B* b; C* c; b=static_cast<B>(a); // 编译不会报错, B类继承A类 c=static_cast<B>(a); // 编译报错, C类与A类没有任何关系 return 1; }
2、const_cast操作不能在不同的种类间转换。
相反,它仅仅把一个它作用的表达式转换成常量。它可以使一个本来不是const类型的数据转换成const类型的,或者把const属性去掉。
3、reinterpret_cast: 有着和C风格的强制转换同样的能力。它可以转化任何内置的数据类型为其他任何的数据类型,也可以转化任何指针类型为其他的类型。它甚至可以转化内置的数据类型为指针,无须考虑类型安全或者常量的情形。不到万不得已绝对不用。4、dynamic_cast:
(1)其他三种都是编译时完成的,dynamic_cast是运行时处理的,运行时要进行类型检查。#include<iostream> #include<cstring> using namespace std; class A { public: virtual void f() { cout<<"hello"<<endl; }; }; class B:public A { public: void f() { cout<<"hello2"<<endl; }; }; class C { void pp() { return; } }; int fun() { return 1; } int main() { A* a1=new B;//a1是A类型的指针指向一个B类型的对象 A* a2=new A;//a2是A类型的指针指向一个A类型的对象 B* b; C* c; b=dynamic_cast<B*>(a1);//结果为not null,向下转换成功,a1之前指向的就是B类型的对象,所以可以转换成B类型的指针。 if(b==NULL) { cout<<"null"<<endl; } else { cout<<"not null"<<endl; } b=dynamic_cast<B*>(a2);//结果为null,向下转换失败 if(b==NULL) { cout<<"null"<<endl; } else { cout<<"not null"<<endl; } c=dynamic_cast<C*>(a);//结果为null,向下转换失败 if(c==NULL) { cout<<"null"<<endl; } else { cout<<"not null"<<endl; } delete(a); return 0; } 详细出处参考:http://www.jb51.net/article/36914.htm
原文:http://blog.csdn.net/oktears/article/details/19428393