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;
		//这个才是对的
	}
};
相关推荐
brave_zhao10 分钟前
nginx的进程架构
java·学习·nginx
枫零NET15 分钟前
跟着OpenCode学习Pi Coding Agent-05-Agent的类型系统
人工智能·学习
Day(AKA Elin)18 分钟前
【Day】MTP(Multi Token Prediction)技术学习
python·深度学习·学习·llama
lbb 小魔仙24 分钟前
MuMu 模拟器 6.0 硬核测评:这次升级确实不一样
java·开发语言·模拟器·mumu·硬核测评
r_oo_ki_e_39 分钟前
Java 线程池
java·开发语言
枫零NET1 小时前
跟着OpenCode学习Pi Coding Agent-06-Agent循环
学习
小弥儿1 小时前
GitHub今日热榜 | 2026-07-09:OfficeCLI 以 92% 日增幅入围
学习·开源·github
KuaCpp1 小时前
C++进程(下)
c++
糖果店的幽灵1 小时前
从 GPT Researcher 学习 LangChain
gpt·学习·langchain
杜子不疼.1 小时前
【Qt初识】信号槽(二):自定义信号函数与槽函数
开发语言·qt