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);
相关推荐
weixin_464307632 小时前
QT智能指针
java·数据库·qt
沐知全栈开发2 小时前
PHP Math: 精通PHP中的数学函数与应用
开发语言
架构师沉默2 小时前
程序员如何避免猝死?
java·后端·架构
吴声子夜歌2 小时前
JavaScript——call()、apply()和bind()
开发语言·前端·javascript
平凡灵感码头2 小时前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
Zzxy2 小时前
快速搭建SpringBoot项目并整合MyBatis-Plus
java·spring boot
hz_zhangrl2 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
星如雨グッ!(๑•̀ㅂ•́)و✧2 小时前
WebFlux onErrorContinue 和 onErrorResume使用详解
java·人工智能
电商API&Tina2 小时前
电商数据采集API接口||合规优先、稳定高效、数据精准
java·javascript·数据库·python·json
兮℡檬,3 小时前
答题卡识别判卷
开发语言·python·计算机视觉