C方式的强制类型转换
代码示例
#include <stdio.h>
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);
return 0;
}
程序运行结果
C语言强制类型转换存在的问题
1、过于粗暴
任意类型之间都可以进行转换,编译器很难判断其正确性。
2、难于定位
在源码中无法快速定位所有使用强制类型转换的语句。
新式类型转换
C++将强制类型转换分为4种不同的类型。
static cast 强制类型转换
用于基本类型间的转换。不能用于基本类型指针间的转换。
用于有继承关系类对象之间的转换和类指针之间的转换。
const cast 强制类型转换
用于去除变量的只读属性。
强制转换的目标类型必须是指针或引用。
dynamic_ cast 强制类型转换
用于指针类型间的强制转换。
用于整数和指针类型间的强制转换。
reinterpret_ cast 强制类型转换
用于有继承关系的类指针间的转换。
用于有交叉关系的类指针间的转换。
具有类型检查的功能。需要虚函数的支持。
语法:
xxx_ cast< Type >( Expression)
代码示例
#include <iostream>
using namespace std;
// 声明函数
void static_cast_demo()
{
int i = 0x12345;
char c = 'c';
int* pi = &i;
char* pc = &c;
c = static_cast<char>(i);
// 不能在基本类型的指针之间转换
// pc = static_cast<char*>(pi);
}
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);
k = 5;
printf("k = %d\n", k);
printf("j = %d\n", j);
y = 8;
// 输出结果
cout << "x" << x << endl;
cout << "y" << y << endl;
cout << "&x" << &x << endl;
cout << "&y" << &y<< endl;
}
void reinterpret_cast_demo()
{
int i = 0;
char c = 'c';
int* pi = &i;
char* pc = &c;
pc = reinterpret_cast<char*>(pi);
pi = reinterpret_cast<int*>(pc);
pi = reinterpret_cast<int*>(i);
// 不能够将int转换为char
// c = reinterpret_cast<char>(i);
}
void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
// 类指针的转换,需要虚函数的支持
// char* pc = dynamic_cast<char*>(pi);
}
int main()
{
// 调用函数
static_cast_demo();
const_cast_demo();
reinterpret_cast_demo();
dynamic_cast_demo();
return 0;
}
程序运行结果
转换类型方式总结
C方式的强制类型转换
过于粗暴
潜在的问题不易被发现
不易在代码中定位
新式类型转换
编译器能够帮 助检查潜在的问题
非常方便的在代码中定位
支持动态类型识别( dynamic_ cast)