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);
相关推荐
失业写写八股文6 分钟前
如何选择栈与堆?堆跟栈的区别
java·后端
xinxiyinhe6 分钟前
Python在图像处理领域的第三方库支持(三)
开发语言·图像处理·python
张张张31220 分钟前
3.25学习总结 抽象类和抽象方法+接口+内部类+API
java·学习
Awesome Baron21 分钟前
LeetCode hot 100 每日一题(16)——240. 搜索二维矩阵 II
java·leetcode·矩阵
云只上23 分钟前
为什么后端接口返回数字类型1.00前端会取到1?
java·前端
陳長生.26 分钟前
JAVA EE_多线程-初阶(一)
java·开发语言·java-ee
大模型铲屎官26 分钟前
如何用C#继承提升游戏开发效率?Enemy与Boss案例解析
开发语言·unity·c#·游戏引擎·游戏开发·boss·enemy
十五年专注C++开发29 分钟前
双指针技巧在C++中的应用:从基础到进阶
开发语言·数据结构·c++
aimmon43 分钟前
Rust从入门到精通之精通篇:24.高级异步编程
开发语言·算法·rust
天机️灵韵1 小时前
Java动态生成Word终极指南:poi-tl与Aspose.Words性能对比及选型建议
java·vscode·word·模板