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);
相关推荐
LXS_3574 分钟前
C++常用容器(下)---stack、queue、list、set、map
开发语言·c++·学习方法·改行学it
愚者游世7 分钟前
list Initialization各版本异同
开发语言·c++·学习·程序人生·算法
.小墨迹8 分钟前
apollo中车辆的减速绕行,和加速超车实现
c++·学习·算法·ubuntu·机器学习
Poetinthedusk16 分钟前
WPF应用跟随桌面切换
开发语言·wpf
shejizuopin20 分钟前
基于SSM的高校旧书交易系统的设计与实现(任务书)
java·mysql·毕业设计·论文·任务书·基于ssm的·高校旧书交易系统的设计与实现
Hello World . .21 分钟前
数据结构:二叉树(Binary tree)
c语言·开发语言·数据结构·vim
恒者走天下21 分钟前
操作系统内核项目面经分享
c++
WBluuue21 分钟前
数据机构与算法:dp优化——倍增优化
c++·算法·leetcode·动态规划
叫我辉哥e123 分钟前
新手进阶Python:办公看板升级交互式可视化+移动端适配+多终端同步
开发语言·python
1candobetter28 分钟前
JAVA后端开发——Spring Boot 组件化自动配置机制
java·开发语言·spring boot