C++四种类型转换全解析,面试必考的类型转换题!

C++四种类型转换全解析,面试必考的类型转换题!

C++的四种类型转换是面试高频考点。本文系统讲解static_cast、dynamic_cast、const_cast、reinterpret_cast的使用场景和注意事项,附带大量代码示例!

1. 为什么需要类型转换

1.1 C风格类型转换的问题

// C风格转换:不安全,难以识别
int a = 10;
double b = (double)a;        // 基本类型转换
char* p = (char*)"hello";    // 指针转换,危险!
Base* base = new Derived;
Derived* d = (Derived*)base; // 向下转型,不安全

C风格转换的问题:

  • 转换意图不明确
  • 编译器难以检查
  • 代码可读性差
  • 所有转换混在一起,难以区分

1.2 C++四种类型转换

转换类型 用途 运行时检查 安全性
static_cast 编译期类型转换
dynamic_cast 安全的向下转型
const_cast 去除const/volatile
reinterpret_cast 低级别位转换 极低

2. static_cast

2.1 基本用法

// 1. 基本类型转换
int a = 10;
double b = static_cast<double>(a); // int -> double

// 2. 指针向上转型(安全)
class Base {
   
   };
class Derived : public Base {
   
   };

Derived* d = new Derived;
Base* b = static_cast<Base*>(d); // 向上转型,安全

// 3. 指针向下转型(不安全,需要程序员保证)
Base* base = new Derived;
Derived* d2 = static_cast<Derived*>(base); // 向下转型,不安全

// 4. void* 与其他指针互转
void* p = nullptr;
int* ip = static_cast<int*>(p); // void* -> int*

2.2 使用场景

// 场景1:显式类型转换,提高代码可读性
double result = static_cast<double>(numerator) / denominator;

// 场景2:类层次结构中的向上转型
class Animal {
   
   
public:
    virtual void speak() {
   
    cout << "Animal" << endl; }
};
class Dog : 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值