C++-C++中的几种cast

文章目录

static_cast

所谓static,意思是在编译期进行的转换,static_允许如下转换:

POD类型互转

int, float, bool等POD类型互转

cpp 复制代码
bool a = true;
int b = static_cast<int>(a);

任意指针类型与void*互转

cpp 复制代码
bool a = 123;
// int* b = static_cast<int*>(&a);  // 编译出错,static_cast不允许不相关类型指针的互转
void* p = &a;
int* b = static_cast<int*>(p);  // 通过先转为void *再转int*是可以通过编译的

基类继承类之间的互转

cpp 复制代码
class Base {};
class Derived : public Base {};

Base b;
Derived* d = static_cast<Derived*>(&b);

具有目标类型转换函数的类/单参数的构造函数

cpp 复制代码
class integer {
    int x;

public:
    // constructor
    integer(int x_in = 0)
        : x{ x_in }
    {
        cout << "Constructor Called" << endl;
    }

    // user defined conversion operator to string type
    operator string()
    {
        cout << "Conversion Operator Called" << endl;
        return to_string(x);
    }
};
integer obj;
string str2 = static_cast<string>(obj);  // integer类到string,通过类型转换函数
integer obj = static_cast<integer>(30);  // int到integer类,通过构造函数

dynamic_cast

dynamic与static相对,在运行时根据内存中的实际对象类型进行类型转换,用于具有虚函数的基类和子类之间的转换,通常在基类指针向下转换到派生类指针时使用。

cpp 复制代码
class Base
{virtual void f() {}};
class Derived : public  Base
{
};

Base* b = new Derived;
Derived* d = static_cast<Derived*>(b);

reinterpret_cast

任意类型之间的转换,主要在底层代码中使用

cpp 复制代码
bool b = true;
int* a = reinterpret_cast<int*>(b);
相关推荐
wjs20241 分钟前
C# 常量
开发语言
Ma_Hong_Kai5 分钟前
CMFCRibbonBar
开发语言·visualstudio·mfc
jaysee-sjc7 分钟前
【练习十二】Java实现年会红包雨小游戏
java·开发语言·算法·游戏·intellij-idea
LONGZETECH17 分钟前
新能源汽车充电设备装配与调试仿真教学软件 技术解析与教学落地
开发语言·系统架构·汽车·汽车教学软件·智能网联汽车软件
indexsunny20 分钟前
互联网大厂Java求职面试实战:核心技术与业务场景解析
java·spring boot·redis·微服务·kafka·互联网大厂·面试技巧
User_芊芊君子22 分钟前
2026最新Python+AI入门指南:从零基础到实战落地,避开90%新手坑
开发语言·人工智能·python
小涛不学习23 分钟前
Java 后端核心框架面试题(Spring / SpringMVC / MyBatis / MyBatis-Plus)
java·spring·mybatis
程序猿大波24 分钟前
基于java,SpringBoot和Vue餐饮公司食堂管理系统设计
java·vue.js·spring boot
艾莉丝努力练剑27 分钟前
【脉脉】AI创作者崛起:掌握核心工具,在AMA互动中共同成长
运维·服务器·c++·人工智能·安全·企业·脉脉
似水明俊德28 分钟前
01-C#.Net-泛型-学习笔记
java·笔记·学习·c#·.net