自学内容网 自学内容网

C/C++语言基础--C++四大类型转换讲解

本专栏目的

  • 更新C/C++的基础语法,包括C++的一些新特性

前言

  • 通过前面几节课,我们学习了抽象、封装、继承、多态、异常等概念,这一篇我们将继续学习C++的类型转换,和C语言还有很大区别的
  • 在本节课最后,也简要说了一下在计算机视角上看类型是什么样子的
  • C语言后面也会继续更新知识点,如内联汇编;
  • 欢迎收藏 + 关注,本人将会持续更新。

类型转换

问题抛出(C语言的缺陷)

📝 首先先回忆一下C++中的类型转换,再C语言中,类型转换很简单,只需要再需要修改类型的地方前添加(datatype),datatype为要转换的类型 ,但是这样其实是很不严谨的,我们来看一下这样一个案例==(C语言中)==:

#include <stdio.h>

int main()
{
const int a = 10;
const int* p = &a;

int* pp = (int*)p;

*pp = 20;

printf("%d %d %d\n", a, *p, *pp);
}

📤 输出:

20 20 20

这个时候我们来分析一下,变量a是一个const修饰的变量,我们也声明了一个指针常量p,指向变量a的地址,这个时候我们通过强制转换,强制转换成==int*==类型,将指针p转换成普通指针pp,这个时候通过指针pp修改变量a的值,然后输出,通过输出发现,将常量a修改成功了这显然不符合常理,💁‍♂💁‍♂💁‍♂,注意:这个时候如果用CPP文件去运训,会得到以下结果

10 20 20

这是因为C++他做了优化,会将a变量再只读区域储存一份,这个可以参考之前的博客: C/C++的不同

所以,C++为了规范C中的类型转换,加强类型转换的可视性,引入了四种强制类型转换操作符:

  • static_cast:
  • reinterpret_cast:
  • const_cast:
  • dynamic_cast:

下面我们分别来学习这几个类型转换。

static_cast

static_cast(expression),该运算符把expression转换为type-id类型

static_cast关键字是再编译阶段完成的,不提供动态类型检查,所以再我们写的时候就需要经量保证这个类型之间是可以转换的,防止出现上行转换这样的,当然现在很多编译器都有自己的检查机制,会自动帮我们检查,如vs,但是linux上编程是不会的。

🌾 应用:编译器隐式执行任何类型转换都可由static_cast显示完成,编译器隐式:编译器再编译的时候自动帮我们操作,所以我们需要保证再写的时候需要保证可以转换,这个就得看经验积累了,常用如下

  • ⚾️ 基本类型转换

    double score = 59.5;
    int nScore = static_cast<int>(score);
    
  • ⚡️ void指针和其他类型指针之间的转换

    void* p = new int(20);
    int* pi = static_cast<int*>(p);
    void* pc = static_cast<void*>(pi);//这里可以隐式转换,可以省略static_cast
    delete p;
    
  • 🅿️ 用于基类派生类之间指针、引用的转换

    class Base
    {
    public:
    virtual void show()
    {
    std::cout << "Base " << std::endl;
    }
    };
    
    class Derive :public Base
    {
    char* name = nullptr;
    public:
    Derive()
    {
    name = new char[5]{ "玩蛇" };
    }
    ~Derive()
    {
    delete name;
    }
    void print()
    {
    std::cout << "Derive " << name << std::endl;
    }
    };
    
    • 🆙 **上行转换:**把派生类指针、引用转为基类的指针、引用(可以自动隐式转换)
    //指针
    Derive* derive = new Derive;
    Base* base = static_cast<Derive*>(derive);   // 转换成基类
    //引用
    Derive& refDerive = *derive;
    Base& refBase = static_cast<Base&>(refDerive);  // 转换成基类
    
    delete derive;
    
    • ⏬ **下行转换:**把基类指针、引用转为派生类的指针、引用(必须强制静态转换)
    Base* base = new Base;
    Derive* derive = static_cast<Derive*>(base);
    derive->print();
    
    delete base;
    

    ⚠️ **注意:**下行转换使用static_cast 不安全,请使用dynamic_cast(不安全:因为不知道基类的指针,到底是不是指向的要转换的派生类对象,如果不是,访问数据成员会有错误)

reinterpret_cast

这个可以用于:任意指针之间的转换,不安全,不推荐使用,了解即可。

主要用于以下六种情况:

  • 任意类型指针之间的转换

    int* p = nullptr;
    char* pc = reinterpret_cast<char*>(p);
    
  • 指针转整型,整型转指针

    int* p = nullptr;
    uint64_t a = reinterpret_cast<uint64_t>(p);//x64 指针是8个字节,所以要用uint64_t保存,否则可能会丢失数据
    double* pd = reinterpret_cast<double*>(a);
    
  • 函数指针也可以转换

    uint64_t funMax = reinterpret_cast<uint64_t>(_max);
    cout<<reinterpret_cast<int(*)(int, int)>(funMax)(2, 3);
    
    int _max(int a, int b)
    {
    return a > b ? a : b;
    }
    
  • 一个官方案例

    int arr[10];
    for (int i = 0; i < 10; i++)
    {
    cout << arr+i <<"  " <<hex<< ::hash(arr+i) << endl;;
    }
    
    uint32_t _hash(void* p)
    {
    uint64_t val = reinterpret_cast<uint64_t>(p);
    return val ^ (val >> 32);
    }
    

const_cast

const_cast用来移除类型的const属性,所以,const_cast 中的类型必须是指针、引用或指向对象类型成员的指针(引用的本质也是常量指针).

  • const指针、引用不能直接赋值给非const的对象,需要去掉const之后再赋值

    const char* name = "hello";
    char* pname = const_cast<char*>(name);  // 转化成非const类型
    
    const int& refA = 8;
    int& refB = const_cast<int&>(refA);
    
  • 可以在类的const函数里面修改成员变量

    class Integer
    {
    private:
    int number;
    public:
    Integer(int number = 0)
    :number(number)
    {
    }
    operator int()const   // const:说明里面的不允许有变量发送改变
    {
    const_cast<int&>(number)++;//必须去掉const才能修改
            const_cast<Integer*>(this)->number++;
    return number;
    }
    };
    
    Integer num = 10;
    int n = num;//11
    

dynamic_cast

dynamic_cast用于有继承关系的多态类(基类必须有虚函数)的指针或引用之间的转换,即,父子类之间的转换,且安全。

  • 通过dynamic_cast,将派生类指针转换为基类指针(上行转换),这个操作与static_cast的效果是一样的。
  • 通过dynamic_cast,将基类指针转换为派生类指针(下行转换),dynamic_cast具有类型检查的功能,比static_cast更安全如果转换的是指针,失败时会返回空指针;如果转换的是引用,会抛出std::bad_cast异常

🙈 使用场景:

  • 指针转换,转换失败返回nullptr,更安全

    Animal* dog = new Dog;
    dog->cry();
    //转成实际的类型
    Dog* d = dynamic_cast<Dog*>(dog);
    if (!d)
    std::cout << "dog is not Dog" << std::endl;
    d->cry();
    //尝试转成其他子类,失败返回nullptr
    Cat* cat = dynamic_cast<Cat*>(dog);    // 子转化成父
    if (!cat)
    std::cout << "dog is not Cat";
    else
    cat->cry();
    
  • 转换引用,转换失败抛异常std::bad_cast,更安全

    Animal& refA = *dog;
    //转成实际的类型
    Dog& refD = dynamic_cast<Dog&>(refA);  // 父转化成子
    refD.cry();
    //尝试转成其他子类,失败抛异常
    Cat& refC = dynamic_cast<Cat&>(refA);
    refC.cry();
    

小结与类型转换本质简说

  • static_cast:最常用,用于普通类型转换
  • reinterpret_cast:任意指针之间转换,不推荐使用
  • const_cast:用去去掉const属性
  • dynamic_cast:主要用于基类与派生类之间的转换

👀👀👀 其实再计算机内部,他是没有类型这一概念的,汇编也没有类型这一概念,类型是高级语言自己抽象出来的,类型转换就是告诉编译器这个变量属于什么类型,这样再转化成汇编的时候就可以调用不同类型的汇编指令了,当然还有很多要注意的,比如说:无符号与有符号之间的转换,-1类型转换如果从位的角度来看,转化成1,就不单单只是加个负号这么简单了,这个本人会更新后面会更新《深入理解计算机系统》这本书学习笔记,到时候会有详细的讲解🔈。


原文地址:https://blog.csdn.net/weixin_74085818/article/details/143028879

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!