cast 转换符
语法: typename1 val1 = (typename1)val2;
把一个整型值给一个浮点变量,编译器会暗地里调一个函数,或者更可能插入代码来把整型值付给一个浮点变量
#include <iostream>
int main()
{
int b = 200;
unsigned long a = (unsigned long int)b;
float c = (float)200;
float d = float(200);
return 0;
}
static_cast const_cast dynamic_cast reinterpret_cast 转换符
显示转换从语义上将就是对编译器说“忘记类型检查,把它当做是其它类型”
- static_cast 用于
非强制类型转换(安全的转换)
不太安全的类型转换(信息丢失)
定义明确的变换 (void *)
#include <iostream>
int main()
{
int i = 10;
long l;
float f;
//01 安全的类型转换,int->long 无信息损失
l = i;
//个人倾向于这种形式,表明作者清楚的知道自己在做什么
l = static_cast<long> (i);
//02 窄化转换,可能有信息的损失,推崇这种形式
i = static_cast<int> (l);
i = static_cast<int> (f);
char c = static_cast<char> (l);
//03 void* 指针理论上可以赋值给任意类型指针,存在风险
void *vp = &i;
float *fp = (float*) vp;
//倾向这种形式,表明作者清楚的明白面临的风险
fp = static_cast<float*> (vp);
//04 类类型 向上造型,不在此处说明
return 0;
}
- const_cast
去常转换(const修饰词) 与 去易转换(自己导演的黑话…volatile修饰词)
#include <iostream>
int main()
{
int const i = 0;
//带有常属性的变量指针 不能直接 赋值给非常属性的指针 --编译报错
//int *j = &i;
/*下面这两种写法表明作者清楚 此编程风格带来的风险,推荐第二种风格*/
int *j = (int *)&i;
int *k = const_cast<int*> (&i);
/*下面这两种写法表明作者清楚 此编程风格带来的风险,推荐第二种风格*/
volatile int m = 0;
u = (int*) (&m);
int *u = const_cast<int*> (&m);
//u = &m;
return 0;
}
- static dynamic reinterpret_cast 对象指针应用中的比较
类型重解 完全把一种类型当做成另一种类型进行转换(通常是针对指针),是危险的一种转换方式,工程实践中见到的很少。
reinterpret_cast 和static_cast 相同处在于应用领域,通常在多重继承的场合,但是又有所不同
#include <iostream>
using namespace std;
class A {
virtual void foo (void) {}
};
class B : public A {};
class C : public B {};
class D {};
int main (void) {
B b;
A* pa = &b;
A& ra = b;
cout << "pa = " << pa << endl;
B* pb = dynamic_cast<B*> (pa);
cout << "pb = " << pb << endl;
C* pc = dynamic_cast<C*> (pa);
cout << "pc = " << pc << endl;
if (! pc) {
cout << "类型转换失败!" << endl;
// ...
}
try {
C& rc = dynamic_cast<C&> (ra);
}
catch (exception& ex) {
cout << "类型转换失败:" << ex.what()
<< endl;
// ...
}
D* pd = dynamic_cast<D*> (pa);
cout << "pd = " << pd << endl;
cout << "--------" << endl;
pb = static_cast<B*> (pa);
cout << "pb = " << pb << endl;
pc = static_cast<C*> (pa);
cout << "pc = " << pc << endl;
// pd = static_cast<D*> (pa);
// cout << "pd = " << pd << endl;
cout << "--------" << endl;
pb = reinterpret_cast<B*> (pa);
cout << "pb = " << pb << endl;
pc = reinterpret_cast<C*> (pa);
cout << "pc = " << pc << endl;
pd = reinterpret_cast<D*> (pa);
cout << "pd = " << pd << endl;
return 0;
}
}