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;
		//这个才是对的
	}
};
相关推荐
郝学胜-神的一滴18 分钟前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy
不积跬步无以至千里mmbb2628 分钟前
【软件工艺师 rust相关课程】
开发语言·后端·rust
SEO_juper30 分钟前
HTTPS 混合内容检查工具:页面全站 https 了,但还有 http 资源在拖后腿
开发语言·网络协议·http·https·node.js·json·bash
软件技术NINI1 小时前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习
神一样的老师2 小时前
WS63 BLE 配网实战:用 Python 在 PC 上替代手机完成 WiFi 配网
开发语言·python·智能手机
geovindu3 小时前
python: Decision Tree
开发语言·后端·python·决策树
时间的情敌3 小时前
Three.js 工业场景性能优化合集|大批量管线、InstancedMesh 实例化、合并 Geometry、显存释放
开发语言·javascript·性能优化·three.js
源码手记4 小时前
基于微信小程序的驾考刷题学习系统-毕设源码
学习·微信小程序·课程设计
小李不想当小白4 小时前
HAL库之定时器输出比较(STM32 HAL库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
步峰代理-盾山4 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫