1.c方式的强制类型转换
—-(Type)(Expression)
—-Type(Expression)
存在的问题:1.过于粗暴,任意类型之间都可以进行转换,编译器很难判断其正确性
2.难于定位,在源码中无法快速定位所有使用强制类型转换的语句
typedef void(PF) (int);struct Point{int x;int y;};int main(){int v = 0x12345;PF* pf = (PF*)(v); //强制转换为函数指针char c = char(v);Point* p = (Point*)v;pf(5);printf("p->x = %d\n",p->x);printf("p->y = %d\n",p->y);}//过于粗暴,编译通过,但是运行发送段错误
强制类型转换在实际工程中是很难避免的,如何进行更加安全可靠的转换?
2.新式类型转换
c++将强制类型转换分为4种不同的类型
强制类型转换:static_cast
const_cast
dynamic_cast
reinterpret_cast
用法:xxx_cast
记住以下四个强制类型转换的规则!!!!!!!!
static_cast强制类型转换
—-用于基本类型间的转换
—-不能用于基本类型指针间的转换
—-用于有继承关系类对象之间的转换和类指针之间的转换
const_cast强制类型转换
—-用于去除变量的只读属性
—-强制转换的目标类型必须是指针或引用
reinterpret_cast强制类型转换
—-用于指针类间强制转换
—-用于整数和指针间的强制转换
dynamic_cast强制类型转换
—-用于有继承关系的类指针间的转换
—-用于有交叉关系的类指针间的转换
—-具有类型检查的功能
—-需要虚函数的支持
//新型类型转换初体验#include <stdio.h>void static_cast_demo(){int i = 0x12345;char c = 'c';char* pc = &c;int* pi = &i;c = static_cast<char>(i);pc = static_cast<char*>(pi); //invalid static_cast from type ‘int*’ to type ‘char*’}void const_cast_demo(){const int& j = 1;int& k = const_cast<int&>(j);const int x = 2;int& y = const_cast<int&>(x);int z = const_cast<int>(x); //const_cast去掉只读属性,目标必须是指针或者引用//invalid use of const_cast with type ‘int’, which is not a pointerk = 5;printf("k = %d\n",k);printf("j = %d\n",j);y = 0;printf("y = %d\n",y);printf("x = %x\n",x);printf("&y = %p\n",&y);printf("&x = %p\n",&x);}void reinterpret_cast_demo(){char c = 'c';int i = 0;int* pi = &i;char* pc = &c;pc = reinterpret_cast<char*>(pi);pi = reinterpret_cast<int*>(pc);pi = reinterpret_cast<int*>(i);c = reinterpret_cast<char>(i); //error invalid cast from type ‘int’ to type ‘char’}void dynamic_cast_demo(){int i = 0;int* pi = &i;char* pc = dynamic_cast<char*>(pi);//error cannot dynamic_cast ‘pi’ (of type ‘int*’) to//type ‘char*’ (target is not pointer or reference to class)}
小结:
1.c方式的强制类型转换
—-过于粗暴
—-潜在问题不易被发现
—-不易在代码中定位
2.新式类型转换以c++关键字 的方式出现
—-编译器能够帮助检查潜在的问题
—-非常方便的在代码中定位
—-支持动态类型识别(dynamic_cast)
