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();
}
相关推荐
AI_661465974 小时前
副业平台收益效率评估:实验设计、指标体系与数据分析框架
经验分享·笔记
谭欣辰4 小时前
详细讲解 C++ 状压 DP
开发语言·c++·动态规划
阿星_4 小时前
Windows Subsystem for Linux (WSL) 运行 Firefox 浏览器时遇到中文乱码的解决方法
笔记
William_wL_4 小时前
【C++】stack和queue的使用和实现(附加deque的简单介绍)
开发语言·c++
山甫aa4 小时前
二叉树遍历----从零开始的数据结构
数据结构·c++·二叉树
淘矿人4 小时前
2026年4月-DeepSeek V4 vs GPT-5.5深度对比测评:weelinking一键切换实测
服务器·数据库·人工智能·python·gpt·学习·php
一只机电自动化菜鸟4 小时前
一建机电备考笔记(27)测量技术—仪器(含考频+题型)
经验分享·笔记·学习·职场和发展·求职招聘·课程设计
xiaoxiaoxiaolll4 小时前
《Light: Science & Applications》SSH模型能带首次在光子芯片上直接读出:混合频率架构赋能拓扑量子模拟
学习
Be for thing4 小时前
Android Studio 常用快捷键总结
android·学习
茜子.Java5 小时前
postman 进阶使用教程
学习