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);
相关推荐
bitbrowser10 小时前
Claude 账号频繁被封?转向国内可直接使用的 AI 工具
开发语言·php
jvmind_dev11 小时前
Java GC 实战指南(番外篇):被忽视的隐形杀手 —— Class Unloading 如何拖垮 GC
java·后端
An_s11 小时前
机器学习python之识别图中物品信息
java·linux·开发语言
小雪_Snow11 小时前
JavaScript 中的三种常用事件
开发语言·前端·javascript
米罗篮11 小时前
矩阵快速幂 (Exponentiation By Squaring Applied To Matrices)
c++·线性代数·算法·矩阵
肖爱Kun11 小时前
C++设计策略模式
开发语言·c++·策略模式
AIGS00111 小时前
跨越语义鸿沟:企业本体语义平台的构建与落地
java·人工智能·python·机器学习·人工智能ai大模型应用
灯澜忆梦11 小时前
GO_面向对象_方法
开发语言·golang
布朗克16811 小时前
Go 入门到精通-16-字符串深入
开发语言·后端·golang·字符串
北冥you鱼12 小时前
Go flag 包详解:从命令行解析到实战应用
开发语言·后端·golang