C++类型转换 static_cast 、 reinterpret_cast、dynamic_cast、const_cast

本文深入探讨了C++中的四种类型转换操作符:static_cast、reinterpret_cast、dynamic_cast和const_cast的功能与使用场景,通过具体代码示例展示了它们在实际编程中的应用,包括基本类型转换、指针类型转换及多态类之间的安全转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         1)static_cast<>()   静态类型转换,编译的时c++编译器会做类型检查;基本类型能转换 但是不能转换指针类型

         2)若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释

         3)一般性结论:

C语言中  能隐式类型转换的,在c++中可用 static_cast<>()进行类型转换。因C++编译器在编译检查一般都能通过;

C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释。总结:static_cast<>()和reinterpret_cast<>() 基本上把C语言中的 强制类型转换给覆盖

reinterpret_cast<>()很难保证移植性。

         4)dynamic_cast<>(),动态类型转换,安全的基类和子类之间转换;运行时类型检查

         5)const_cast<>(),去除变量的只读属性

实例:

#include <iostream>
using namespace std;
class Tree
{

};
class Animal
{
public:
    virtual void cry() = 0;
};
class Dog :public Animal

public:
    virtual void cry()
    {
        cout << "汪汪" << endl;
    }
    void doHome()
    {
        cout << "看家" << endl;
    }
};
class Cat :public Animal
{
private:
    virtual void cry()
    {
        cout << "喵喵" << endl;
    }
public:
    void dothing()
    {
        cout << "抓老鼠" << endl;
    }
};
void print(const char * p)
{
    //p[0] = 'H';  //报错,不能修改,因为p是常量指针,其内存空间不能修改
    char *base = NULL;
    base = const_cast<char*>(p);
    base[0] = 'H';
    cout << p << endl;
}

void main()
{
    char p[] = "huangxiangao";
    char *p1 = "huangxiangao";
    print(p);  //正常修改
    //print(p1);  //产生中断,因为p1是常量,没有内存空间,根本不能修改
    system("pause");
}

void playObj(Animal *base)
{
    base->cry();  //发生多态 继承,虚函数重写,父类指针指向子类指针
    Dog *dogp = dynamic_cast<Dog *>(base);
    if (dogp != NULL)
    {
        dogp->doHome();
    }
    Cat *catp = dynamic_cast<Cat *>(base);  //运行时动态判断类型,主要用于父子类之间
    if (catp != NULL)
    {
        catp->dothing();
    }
}
void main02()
{
    Dog d1;
    Cat c1;
    playObj(&d1);
    playObj(&c1);

    Tree t1;
    Animal * base = NULL;
    //base = static_cast<Animal *>(&t1);  //出错
    base = reinterpret_cast<Animal *>(&t1);//编译通过

    system("pause");
}
void main01()
{
    
    int a = 10;
    char b = 'c';
    a = static_cast<int>(b);  //静态编译时类型检查,基本数据类型
    cout << a << endl;
    
    /*
    int a = 10;
    char b = 'c';
    a = reinterpret_cast<int>(b);  //reinterpret_cast 不能将char转成int
    cout << a << endl;
    */
    int *intp =NULL;
    char *charp = "huangxiangao";
    //intp = static_cast<int*>(charp);//错误    1    error C2440: “static_cast”: 无法从“char *”转换为“int *”
    intp = reinterpret_cast<int *>(charp);  //主要是用于指针,有强制转换的意思
    cout << charp << endl;
    cout << intp << endl;

    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值