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);
相关推荐
geovindu20 分钟前
python:DecisionTree
开发语言·后端·python·算法
Cosolar25 分钟前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
ShineWinsu1 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu2 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
IT空门:门主2 小时前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习
闻缺陷则喜何志丹3 小时前
【数论】P10136 [USACO24JAN] Cowlendar S|普及+
c++·数学·数论·洛谷
apcipot_rain3 小时前
某游戏公司C++游开实习 机试复盘
c++·游戏
用户3721574261354 小时前
Java 批量操作 Excel 超链接:添加、读取、修改和删除
java
用户3721574261355 小时前
Java 将 Excel 图表导出为图片:指定图表、批量导出与图表工作表
java
炸膛坦客6 小时前
单片机/C/C++八股:(三十七)指针数组 和 数组指针
c语言·开发语言·c++