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;
		//这个才是对的
	}
};
相关推荐
geovindu7 分钟前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
minglie130 分钟前
幂电枢与幂剩余
学习
优化Henry1 小时前
5G站点AAS-3设备故障排查与处理
运维·学习·5g·信息与通信
小oo呆1 小时前
【学习心得】Python函数参数中的两个特殊分隔符
开发语言·python
x10n91 小时前
微软 VC++ 运行库合集VCRedistPack
开发语言·c++·microsoft·vc++运行库·dll报错
qz_Serene1 小时前
C++:string(底层,常用接口,具体题目,模拟实现)
开发语言·c++
NiceBlueChai1 小时前
Qt 跨线程传递多容器嵌套结构:一次 Release 实测
开发语言·qt
念何架构之路1 小时前
go-grpc逻辑架构图
开发语言·后端·golang
SEO_juper1 小时前
AI 爬虫 robots.txt 检查工具:你的站是不是把 AI 挡在门外了
开发语言·人工智能·爬虫·python·外贸独立站