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;
		//这个才是对的
	}
};
相关推荐
小七在进步6 小时前
string的使用(1)
c++·visual studio
SomeOtherTime6 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood7 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青7 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
kloc10 小时前
聊天室项目入口网关子服务的实现
linux·c++
饮水桶_T11 小时前
JAVA IO流笔记
开发语言·数据结构·算法
csdn_aspnet13 小时前
C++ 3个有序点的方向(Orientation of 3 ordered points)
c++·算法
Felven13 小时前
C. Brr Brrr Patapim
c语言·开发语言
li星野14 小时前
相位补偿学习记录:把被颅骨“打乱“的声波重新对齐
学习
小七在进步14 小时前
string的使用(2)
c++