C++ 四大强制类型转换

在C++中,有四种强制类型转换方式,它们分别是:静态转换(static_cast)、const_cast、动态转换(dynamic_cast)、重新解释转换(reinterpret_cast)。

静态转换(static_cast):

用于非多态类型之间的转换。在进行静态转换时,编译器会在编译时检查转换的合法性,因此在使用时要确保转换是安全的。
静态转换通常用于基本类型之间的转换,例如将整数转换为浮点数,或者在类之间进行显式的转换。

整数转换为浮点数:
int intValue = 10;
double doubleValue = static_cast<double>(intValue);

类之间进行显式的转换:
#include <iostream>
class Base {
public:
    virtual ~Base() {} // 基类析构函数需要为虚函数,以便正确销毁派生类对象
    virtual void print() const {
        std::cout << "Base" << std::endl;
    }
};

class Derived : public Base {
public:
    void print() const override {
        std::cout << "Derived" << std::endl;
    }
};

int main() {
    Base base;
    Derived derived;

    // 在基类指针和派生类指针之间进行静态转换
    Base* basePtr = &base;
    Derived* derivedPtr = static_cast<Derived*>(basePtr);

    // 执行转换后,调用派生类的成员函数
    derivedPtr->print(); // 输出 "Derived"

    return 0;
}

const_cast:

用于添加或删除 const 和 volatile 修饰符。
这种转换通常用于修复传入的函数参数的 const 修饰符,或者在需要时去除 const 修饰符以修改变量。

#include <iostream>

void modifyValue(int* ptr) {
    *ptr = 20;
}

int main() {
    const int constValue = 10;

    // 尝试修改 const 变量会导致编译错误
    // constValue = 20;

    // 使用 const_cast 去除 const 修饰符以修改变量
    int* nonConstPtr = const_cast<int*>(&constValue);
    modifyValue(nonConstPtr);

    // 输出修改后的值
    std::cout << "Modified constValue: " << constValue << std::endl;

    return 0;
}

运行结果:
Modified constValue: 20

动态转换(dynamic_cast):

用于在继承关系中进行安全的向下转型(派生类向基类)和向上转型(基类向派生类)。
动态转换会在运行时进行类型检查,如果转换是不安全的,则返回空指针(对于指针类型)或抛出std::bad_cast异常(对于引用类型)。

Base* basePtr = new Derived();
Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
if (derivedPtr) {
    // 转换成功
} else {
    // 转换失败
}

重新解释转换(reinterpret_cast):

提供了最不安全的类型转换,允许在不同类型之间进行任意位模式的转换。
这种转换通常用于将指针转换为整数类型或者将整数类型转换为指针类型,但使用时要特别小心,因为它会绕过类型系统的检查。

int intValue = 10;
double* doublePtr = reinterpret_cast<double*>(&intValue);

C++中的这四大强制类型转换的函数,我们一般代码中前两个是用的比较多的,使用比较熟悉,后两个大家可以根据自身情况按需使用。

  • 13
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碧 波

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值