reinterpret_cast是为了映射到一个完全不同类型的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄玄虚和其他目的,这是所有映射中最危险的(C++编程思想中的原话)。将static_cast和reinterpret_cast对比一下进行解释,比较容易理解:static_cast 和 reinterpret_cast 操作符修改了操作数类型,但是reinterpret_cast 仅仅是重新解释了给出的对象的比特模型而没有进行二进制转换。例如:
int n=9;
double d=static_cast
上面的例子中, 我们将一个变量从int转换到double。这些类型的二进制表达式是不同的,所以将整数9转换到双精度整数9,static_cast需要正确地为双精度整数d补足比特位。其结果为 9.0。而reinterpret_cast 的行为却不同:
int n=9;
double d=reinterpret_cast
这里, 和static_cast不同,在进行计算以后, d包含无用值。这是因为reinterpret_cast仅仅是复制n的比特位到d, 没有进行必要的分析.
因此, 需要谨慎使用 reinterpret_cast。
[举例]
这个例子,将static_cast和reinterpret_cast对比进行测试,具体的输出参见其中的注释。
1 #include
2 using std::cout;
3 using std::endl;
4 class CBaseX
5 {
6 public:
7 int x;
8 CBaseX() { x = 10; }
9 void foo() { printf(\
10 };
11 class CBaseY
12 {
13 public:
14 int y;
15 int* py;
16 CBaseY() { y = 20; py = &y; }
17 void bar() { printf(\
18 };
19 class CDerived : public CBaseX, public CBaseY
20 {
21 public:
22 int z;
23 }; 24
25 int main(int argc, char *argv[])
26 {
27 float f = 12.3;
28 float* pf = &f; 29
30 //基本类型的转换
31 cout<<\
32 //======static cast<>的使用:
33 int n = static_cast
34 cout<<\
35 //int* pn = static_cast
36 void* pv = static_cast
37 int* pn2 = static_cast
38 cout<<\三者值一样
39 cout<<\是无用值,注意无法使用\因为编译错。 40
41 //======reinterpret_cast<>的使用:
42 //int i = reinterpret_cast
43 //成功编译, 但是 *pn 实际上是无意义的内存,和 *pn2一样
44 int* pi = reinterpret_cast
45 cout<<\值一样
46 cout<<\是无用值,和pn2一样。 47 48
49 //对象类型的转换
50 cout<<\
51 CBaseX cx;
52 CBaseY cy;
53 CDerived cd; 54
55 CDerived* pD = &cd;
56 CBaseX *pX = &cx;
57 CBaseY *pY = &cy;
58 cout<<\ 59
60 //======static_cast<>的使用:
61 CBaseY* pY1 = pD; //隐式static_cast转换
62 //不一样是因为多继承,pD还要前移动以便也指向CBaseX.
63 cout<<\ 64
65 //CDerived* pD1 = pY1;//编译错误,类型 ‘CBaseY*’ 到类型 ‘CDerived*’ 的转换无效
66 CDerived* pD1 = static_cast
67 cout<<\现在 pD1 = pD 68
69 //pX = static_cast
70 pD1 = static_cast
71 cout<<\现在 pD1 = pY-4
72 //======reinterpret_cast<>的使用:
73 CBaseY* pY2 = reinterpret_cast
74 cout<<\ 75
76 //======通过void的转换注意:
77 CBaseY* ppY = pD;
78 cout<<\ 79
80 void* ppV1 = ppY; //成功编译
81 cout<<\ 82
83 //CDerived* ppD2 = ppV1;//编译错误,类型‘void*’ 到类型 ‘CDerived*’的转换无效
84 CDerived* ppD2 = static_cast
85 cout<<\, 但是我们预期 ppD2 = ppY - 4 = pD
86 //ppD2->bar();//系统崩溃,段错误
87 return 0;
88 }
这里,需要注意的地方是:
*第63行中基类指针pY1被赋予子类指针pD后,pY1=pD+4而不是pD,因为pD是多继承,pD还要前移动以便也指向CBaseX.内存布局大致如下:
+CDerived------------------+
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库关于C++中的类型转换操作符(2)在线全文阅读。
相关推荐: