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 }
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复制二进制比特位到目标对象,转换后的值与原始对象无关但是比特位是一样的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具