C++: 四种强制类型转换

本文详细介绍了C++中的四种强制类型转换:const_cast用于修改指针或引用的const属性;static_cast与C语言强制转换类似,但更安全,用于类层次的基类与派生类转换及基本类型转换;dynamic_cast涉及运行时类型信息,主要用于多态性,从基类到可能的派生类安全转换;reinterpret_cast用于无关类型的底层位模式转换,如指针和整数间的转换。
摘要由CSDN通过智能技术生成

一、const_cast

1、常量指针被转化成非常量的指针,并且仍然指向原来的对象;
2、常量引用被转换成非常量的引用,并且仍然指向原来的对象;
3、const_cast一般用于修改指针。如const char *p形式。

#include<iostream>

int main() {
    // 原始数组
    int ary[4] = { 1,2,3,4 };

    // 打印数据
    for (int i = 0; i < 4; i++)
        std::cout << ary[i] << "\t";
    std::cout << std::endl;

    // 常量化数组指针
    const int*c_ptr = ary;
    //c_ptr[1] = 233;   //error

    // 通过const_cast<Ty> 去常量
    int *ptr = const_cast<int*>(c_ptr);

    // 修改数据
    for (int i = 0; i < 4; i++)
        ptr[i] += 1;    //pass

    // 打印修改后的数据
    for (int i = 0; i < 4; i++)
        std::cout << ary[i] << "\t";
    std::cout << std::endl;

    return 0;
}

out print:

1   2   3   4
2   3   4   5

注意:对于在定义为常量的参数,使用const_cast可能会有不同的效果.类似代码如下

#include<iostream>
int main() {
    const int c_val = 233;  //声明为常量类型
    int &use_val = const_cast<int&>(c_val); //使用去const 引用
    int *ptr_val = const_cast<int*>(&c_val);//使用去const 指针

    use_val = 666;  //未定义行为
    std::cout << c_val << "\t" << use_val << "\t" << *ptr_val << std::endl;
    *ptr_val = 110; //未定义行为
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值