c++ 学习之 强制类型转换运算符 const_cast

看例子怎么用

复制代码
int main()
{
	int a = 1;
	int* p = a;
	// 会发生报错
	// 如果学着 c的风格类型转换
	int* pp = (int*)a;
	*pp = 1;  // 编译不报错,但是运行报错


	// const_cast
	const int n = 5;
	const std::string s = "lalal";

	// const cast 只针对指针,引用,this指针,下面的就是错的

	int k = const_cast<int>(n);
	// 下面的才是对的
	int *j = const_cast<int*>(&n);
	int o = const_cast<int&>(n);
}

再看看const_cast在this指针中的用法

复制代码
class Test {
public:
	int a;
	Test(int a) :a(a) {

	}
	void fun(int p) const {
		a = p; // 这句话是错误的
		// 要修改为
		const_cast<Test*>(this)->a = p;
		//这个才是对的
	}
};
相关推荐
没钥匙的锁120 分钟前
05-Java面向对象构造器与封装
java·开发语言
仙人球部落23 分钟前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2401_8949155327 分钟前
Geo搜索优化排名源码部署搭建全流程详解
android·开发语言·flask·php·精选
aaPIXa6221 小时前
C++采样引导优化SPGO——比PGO更智能的编译器决策新方案
java·c++·人工智能
小心亦新1 小时前
STM32学习12--串口2收发数据包
学习
chouchuang1 小时前
day-025-面向对象-上
开发语言·python
Starmoon_dhw1 小时前
题解:P17078 夏日甜点
c++·学习·算法·图论
某不知名網友1 小时前
C/C++动态内存管理,智能指针及RAlI思想。
java·c语言·c++
sunfdf1 小时前
Next.js 新手从零部署到首跑实战指南
开发语言·javascript·ecmascript
菩提树下的打坐1 小时前
接口测试利器:REST Assured + WireMock
学习