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);
相关推荐
Dxy12393102162 小时前
Python的PIL如何转Base64字符串:完整指南
开发语言·python
Howrun7772 小时前
Linux_C++_日志实例
linux·运维·c++
LiRuiJie2 小时前
深入剖析RocketMQ
java·rocketmq
头发还没掉光光2 小时前
C语言贪吃蛇:基于Linux中ncurses库实的贪吃蛇小游戏
linux·c语言·开发语言
BlockChain8882 小时前
SpringBoot实战一:10分钟搭建企业级用户管理系统(20000字完整项目)
java·spring boot·后端
fie88892 小时前
基于MATLAB的时变Copula实现方案
开发语言·matlab
冬奇Lab2 小时前
【Kotlin系列12】函数式编程在Kotlin中的实践:从Lambda到函数组合的优雅之旅
android·开发语言·kotlin
消失的旧时光-19432 小时前
第六课 · 6.1 从 JDBC 到 MyBatis:SQL 工程化是如何发生的?
java·sql·mybatis
写代码的【黑咖啡】2 小时前
Python中的Msgpack:高效二进制序列化库
开发语言·python
梵尔纳多2 小时前
第一个 3D 图像
c++·图形渲染·opengl