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;
		//这个才是对的
	}
};
相关推荐
一尘之中3 小时前
从C语言底层设计到系统架构评估:软件架构知识体系全景
学习·系统架构·ai写作
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
cjhbachelor3 小时前
c++继承
c++
AI玫瑰助手3 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车3 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋3 小时前
C++14特性
开发语言·c++·c++14特性
星夜夏空994 小时前
FreeRTOS学习(4)——内存映射
数据库·学习·mongodb
不羁的木木4 小时前
ArkWeb实战学习笔记05-综合实战:构建混合应用
笔记·学习·harmonyos
橙橙笔记4 小时前
Python的学习第一部分
python·学习
bush45 小时前
嵌入式linux学习记录二
linux·运维·学习