一、C方式的强制类型转换
格式:
(Type)(Expression)
Type(Expression)
先分析如下代码:
#include <stdio.h>
typedef void(FP)(int);
struct Point {
int x;
int y;
};
int main()
{
int v = 0x12345;
PF* pf = (FP*)v;
char c = char(v);
Point* p = (Point*)v;
fp(5);
printf("p->x:%d\n", p->x);
printf("p->y:%d\n", p->y);
}
这段代码用编译器编译的时候不会报任何错误,但是运行结果肯定会很奇怪,甚至产生很严重的后果。而且现这样的错误很难定位他出错的位置,所以C++引入了新的数据类型转换。
C方式强制类型转换存在的问题
1.过于粗暴
任意类型之间都可以进行转换,编译器很难判断其正确性。
2.难于定位
在源码中无法快速定位所有使用强制类型转换的语句。
二、C++强制类型转换
C++强制类型转换分为4种不同的类型:
1. static_cast
a.用于基本类型(bool、enum、int、char、float、double)间的转换
b.不能用于基本类型指针间的转换
c.用于有继承关系类对象之间的转换和类指针之间的转换
示例代码:
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); // Error
}
示例代码2:
class A
{
};
class B:public A
{
};
class C
{
};
int main()
{
A* a = new A;
B* b;
C* c;
b=static_cast<B*>(a); // 编译不会报错, B类继承A类
c=static_cast<B*>(a); // 编译报错, C类与A类没有任何关系
B b1;
A a1 = static_cast<A>(b1); // 编译通过
return 1;
}
2. const_cast
a.用于去除变量的只读属性
b.强制转换的目标类型必须是指针或引用
示例代码:
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); // Error
k = 5;
printf("k = %d\n", k);
printf("j = %d\n", j);
y = 8;
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("&x = %p\n", &x);
printf("&y = %p\n", &y);
}
3. reinterpret_cast
a.用于指针类型间的强制转换
b.用于整数和指针类型间的强制转换
示例代码:
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);
c = reinterpret_cast<char>(i); // Error
}
4. dynamic_cast
a.用于有继承关系的指针间的转换
b.用于有交叉关系的类指针间的转换
c.具有类型检查的功能(转换不成功返回NULL)
d.需要虚函数的支持(定义的类中必须要有虚函数)
示例代码:
void dynamic_cast_demo()
{
int i = 0;
int* pi = &i;
char* pc = dynamic_cast<char*>(pi);
}