C++学习笔记 36 C++风格强制类型转换

一、C语言风格强制类型转换

void traditionalConvert() {
	double a = 5.6;
	int b = a;
	std::cout << b << std::endl;

	double aa = 5.6;
	int bb = (int)a;
	std::cout << b << std::endl;
}

二、C++风格强制类型转换

转换类型 适用场景 安全性
static_cast 非多态类型转换 编译时检查,较安全
dynamic_cast 多态类型安全下行转换 运行时检查,安全
const_cast 修改底层const性 谨慎使用,可能引发未定义行为
reinterpret_cast 不相关类型间指针转换 高风险,依赖平台

1. static_cast 是一个安全的类型转换,它只能转换具有继承关系或密切相关的类型,并且在编译时进行类型检查。
用于转换具有继承关系或密切相关的类型,例如基类和派生类、整数类型和浮点类等。

  • 从基类转换为派生类
  • 从派生类转换为基类
  • 从整数类型转换为浮点类型
  • 从浮点类型转换为整数类型
  • 从枚举类型转换为整数类型
void cPlusPlusConvert() {
	double value = 7.3;
	//静态类型转换,除了转换,还会做一些编译时的检查
	int s = static_cast<int>(value);
	std::cout << s << std::endl;
}
#include<iostream>

class Entity {
public:
	Entity(){}
	virtual ~Entity(){}
};
class Player : public Entity {};
class Enemy : public Entity {};

void testDynamicCast() {
	Player* player = new Player();
	Enemy* enemy = new Enemy();
	Entity* actuallyPlayer = player;

	//1.类型匹配
	//如果 virtual ~Base() 未加 virtual,此出会编译报错:强制要求转换对象必须是多态的
	Player* p1 = dynamic_cast<Player*>(player);

	//2.类型不匹配,返回值是NULL
	Player* p0 = dynamic_cast<Player*>(enemy);
	if (p0) {
		std::cout << "OK \n";
	}
	else {
		std::cout << "Not OK \n";
	}
	//类似于java的 if(instance instanceof Player) {}
	if (dynamic_cast<Player*>(enemy)) {}
}

int main() {
	testDynamicCast();
	return std::cin.get();
}

3. reinterpret_cast 是一个不安全的类型转换,它可以将任何类型的指针转换为任何其他类型的指针,而无需考虑类型安全性。
reinterpret_cast 用于转换不相关的类型,例如指针类型和整数类型、结构体和联合体等。

  • 将指针类型转换为整数类型
  • 将整数类型转换为指针类型
  • 将结构体转换为联合体
  • 将联合体转换为结构体
  • 将函数指针转换为 void* 类型
  • 将 void* 类型转换为函数指针

三、区别及好处

  1. 编译时检查
  2. 可以在代码中按单词搜索(想看类型转换代码,提升性能检查dynamic_cast)
  3. C语言风格的无法搜索
  4. 功能上:它们不做任何C风格类型转换不做的事,在这并不是添加新功能,只是添加了一些语法糖到你的代码中
  5. 在大多数情况下,C++风格的类型转换也不做任何额外的事情,它们只是放进去英语单词

四、参考文章

  1. reinterpret_cast 和 static_cast 的区别
  2. static_cast与dynamic_cast的5大关键区别及使用场景
  3. C++类型转换
posted @ 2025-12-24 10:05  超轶绝尘  阅读(4)  评论(0)    收藏  举报