不同类型数据之间进行赋值
函数调用时,不同类型实参到形参的传值
函数返回了与定义类型不同的数据
//.h int a = 'c';//char类型隐形转换为int类型 void func(int a) { cout << "abc" <
在类型不兼容时,可使用强制类型转换,在两个不同的类型之间完成转换。实现简单,转换功能强大。但由于时强制转换,可能会导致不合理转换,使用会引起各种错误,很危险,慎用~
char ch = 'a'; int b = (int)ch; 或 int b = int(ch);
目标类型变量 = static_cast (源类型变量);
常用于将void* 转换为其它类型的指针
- int* pi = NULL;
- void* pv = pi;
- pi = static_cast<int*>(pv);
dynamic_cast
目标类型变量 = dynamic_cast(源类型变量);
用于类继承层次间的指针或引用转换,支持运行时识别指针或引用。主要是用于安全的向下转型。
- TBaseCast* baseCast;
- TDerived* der = new TDerived();
- baseCast = dynamic_cast
(der);//向上转型本来就是安全的 - //baseCast = der;
-
- TBaseCast* baseCast2 = new TBaseCast();
- TDerived *der2 = dynamic_cast
(baseCast2);//向下转型
const_cast
目标类型变量 = const_cast(源类型变量);
用于去除指针或引用的属性
通过const_cast运算符,也只能将const type转换为type,将const type&转化为type&。
- const int ci = 80;
- int* pci = const_cast<int*>(&ci);// const转换为非const
reinterpret_cast
目标类型变量 = reinterpret_cast(源类型变量);
用于任意类型指针或引用之间的转换
指针和整数之间的转换
用来处理无关类型之间的转换;它会产生一个新值,这个值会有与原始参数完全相同的比特位。其实就是按比特位重新解释为要转换的类型。
- struct T { char type[5];
- char acc[9]; char passwd[7]; };
- char buf[] = "0001\00012345678\000123456";
- T * pt = reinterpret_cast
(buf);//把字符流转化为结构体 - cout << pt->type << endl;
- cout << pt->acc << endl;
- cout << pt->passwd << endl;