隐式类型转换
比如 double f1.0/2;
比如:
couble f=10.2
显式类型转换
(类型说明符)(表达)
比如: double f=double(1)/double(2);
C类型转换的问题
- 任意类型之间都可以转换,编译器无法判断其正确性
- 难与定位,在源代码中无法快速单位
C++的类型转换.
const_cast
用于转换指针或引用,去掉类型的const属性
int main()
{
const int a = 10;
//int* pA = &a;
int* pA=const_cast<int*>(&a)
*pA=100;
return 0;
}
reinterpret_cast
很危险!
重新解释类型,既不检查指向的内容,也不检查指针类型本身 ;但要求转换前后的类型所占用内存大小一致,否则将引发编译时错误…
int Test(){
return 0;
}
int main()
{
typedef void(*FuncPtr)();
FuncPtr funcPtr;
//funcPtr=&Test;
funcPtr=reinterpret_cast<FuncPtr>(&Test);
}
static_cast
用于基本类型转换,有继承关系类对象和类指针之间转换,由程序员来确保转换是安全的,它不会产生动态转换的类型安全检查的开销
int i = 5;
double d= static_cast<double>(i);
double d2 = 5.6;
int i2 = static_cast<int>(d2);
dynamic_cast
只能用于含有虚函数的类,必须用在多态体系中,用于类层次间的向上和向下转化.向下转化时,如果是非法的对于指针返回NULL
class Base
{
public
Base():_i(0){}
virtual void T(){cout<<"Base:T"<<_i<<endl;}
private
int _i;
}
class Derived:public Base
{
public:
Derived:_j(1) (;)
virtual void T(){cout<<"Derived:T"<<_i<<endl;}
private:
int _j;
}
int main(){
Base cb;
Derived cd;
Base* pcb;
Derived* pcd;
//子类->父类
pcb = static_cast<Base*>(&cd)
pcb = dynamic_cast<Base*>(&cd)
if(pcb == NULL){
cout<<"unsafe dynamic_cast from Derived to Base"<<endl;
}
//父类->子类
pcd = static_cast<Derived*>(&cb)
pcd = dynamic_cast<Derived*>(&cb)
if(pcd == NULL){
cout<<"unsafe dynamic_cast from Base to Derived "<<endl;
}
}