C++学习笔记(三十九):c++ 类型转换

本节介绍c++类型转换的相关知识。c++是强类型语言,存在一个类型系统用来将一种类型的数据强制转换成另一种类型。一般有两种方式进行强制类型转换。

  • c风格类型转换

  • int a = 5;

    double value = a;

    double b = 8.4 + (int)value;

  • c++风格类型的转换

  • static_cast:静态类型转换

  • reinterpret_cast:和类型双关类似,将一段内存解释成别的类型

  • dynamic_cast:动态类型转换

  • const_cast:移除或添加变量的const限定

  • 上述四种类型转换均提供编译时检查功能,使用起来更加安全。

  • 代码示例如下:

cpp 复制代码
#include<iostream>
class Base
{
public:
    Base(){}
    virtual ~Base(){}
};
class Derived : public Base
{
public:
    Derived(/* args */){};
    ~Derived(){};
};
class AnotherClass : public Base
{
public:
    AnotherClass(/* args */){};
    ~AnotherClass(){};
};

int main()
{
    double value = 4.3;
    //AnotherClass* s1 = static_cast<AnotherClass*>(&value);  //使用static_cast进行类型转换,会检查类型,static_cast from 'double *' to 'AnotherClass *' is not allowed
    //要解决上述问题,需要使用reinterpret_cast
    AnotherClass* s = reinterpret_cast<AnotherClass*>(&value);

    //dynamic_cast:在做特定类型转换是提供一种安全机制,专门用于继承层次结构的强制类型转换。
    Derived* dervied = new Derived();
    Base* base = dervied;

    AnotherClass* ac = dynamic_cast<AnotherClass*>(base);//dynamic_cast转换会有返回值,可以检测转换是否成功
    if (ac)
    {
        std::cout << "转换成功" << std::endl;
    }
    else
    {
        std::cout << "转换失败" << std::endl; //执行else分支,因为base在代码中是Derived类
    }
    
     

    std::cin.get();
}
相关推荐
樱木Plus18 小时前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
齐生119 小时前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29171 天前
D006 【模板】并查集
笔记
tingshuo29172 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
blasit3 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛6 天前
delete又未完全delete
c++
端平入洛7 天前
auto有时不auto
c++
西岸行者7 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习