C++类型转换:const_cast 和reinterpret_cast

一、Const_cast

const_cast是修改类型的const或者volatile属性。使用该运算方法后可以返回一个纸箱非常量的指针或者引用,使用该运算符后就可以返回一个纸箱非常量的指针(或者引用)。用法如下:

const_cast<type_if>(expression),type_id和expression的类型是一样的。

转换为非常量的指针或者引用还是指向原来的对象,const_cast一般是用来修改底指针。用例如下:

 1 // ConsoleApplication1.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <cstdint>
 6 #include<string>
 7 #include<iostream>
 8 using namespace std;
 9 class person
10 {
11 public:
12    int n_num;
13    virtual void doSomething()
14    {
15       cout << "i am a person" << endl;
16    }
17 };
18 class colorPerson :public person
19 {
20 public:
21    char* mName;
22 };
23 void change(person *person)
24 {
25    colorPerson * cp1 = static_cast<colorPerson*>(person);
26    cout << "start to call cp1" << endl;
27    if (cp1 != NULL)
28    {
29       cp1->doSomething();
30    }
31    else 
32    {
33       cout << "cp1 is null" << endl;
34    }
35    colorPerson *cp2 = dynamic_cast<colorPerson*>(person);
36    cout << "start to call cp2" << endl;
37    if (cp2!= NULL)
38    {
39       cp2->doSomething();
40    }
41    else
42    {
43       cout << "cp2 is null" << endl;
44    }
45 }
46 int main()
47 {
48   const person *pconst=new person();
49    //pconst->n_num = 10;
50    person *noConstP = const_cast<person *>(pconst);
51    noConstP->n_num = 100;
52     return 0;
53 }
View Code

const_cast的目的不是为了让你去修改一个本身被定义为const的值,因为这样做的后果是无法预料的。const_cast的目的是修改一些指针或者引用的权限,如果我们原来无法通过这些指针或者引用修改某一些内存的值,通过const_cast就可以了。

二、reinterpre_cast

reinterpret_cast操作符是修改了操作数的类型,重新解释了给出的对象的比特模型而没有进行二进制的转换。可以理解为view_ashuo或者treat_as的操作。就是把内存中的值进行重新解释。在内存中都是0和1组成的值。而这些0和1具体代表的是什么值,我们就是要看具体的类型了,比如8位bit的ASCII码值,16位或者32位的int值。reinterpret_cast复制二进制比特位到目标对象,转换后的值与原始对象无关但是比特位是一样的。

原文地址:https://www.cnblogs.com/VARForrest/p/15674253.html