static_cast、const_cast、dynamic_cast、reinterpret_cast
1、static_cast 静态类型转换
最常用的类型转换符,在正常状况下的类型转换,如把int转换为float,如:
int i;float f; f=(float)i;//或者
f=static_cast<float>(i);
2、const_cast
用于取出const属性,把const类型的指针变为非const类型的指针
去掉类型的const或volatile属性
const int *fun(int x,int y)
{}
int *ptr=const_cast<int *>(fun(2.3));
主要用于运行时检查该转换是否类型安全,但只在多态类型时合法,即该类至少具有一个虚拟方法。
dynamic_cast与static_cast具有相同的基本语法,dynamic_cast主要用于类层次间的上行转换和下行转换,还可以用于类之间的交叉转换。在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全。
<span style="font-size:14px;">class BaseClass {
public:
int m_iNum;
virtual void foo(){};
//基类必须有虚函数。保持多台特性才能使用dynamic_cast
};
class DerivedClass: public BaseClass {
public:
char *m_szName[100];
void bar(){};
};
BaseClass* pb = new DerivedClass();
DerivedClass *pd1 = static_castDerivedClass *>(pb);
//子类->父类,静态类型转换,正确但不推荐
DerivedClass *pd2 = dynamic_castDerivedClass *>(pb);
//子类->父类,动态类型转换,正确
BaseClass* pb2 = new BaseClass();
DerivedClass *pd21 = static_castDerivedClass *>(pb2);
//父类->子类,静态类型转换,危险!访问子类m_szName成员越界
DerivedClass *pd22 = dynamic_castDerivedClass *>(pb2);
//父类->子类,动态类型转换,安全的。结果是NULL</span>
4、reinterpret_cast
interpret是解释的意思,reinterpret即为重新解释,此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。如:int i; char *ptr="hello freind!"; i=reinterpret_cast<int>(ptr);这个转换方式很少使用
参考:
http://hb.qq.com/a/20110722/001452.htm
http://www.cnblogs.com/BeyondAnyTime/archive/2012/08/23/2652696.html