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);
相关推荐
重生之后端学习5 分钟前
62. 不同路径
开发语言·数据结构·算法·leetcode·职场和发展·深度优先
冬夜戏雪8 分钟前
实习面经摘录(六)
java
把你毕设抢过来11 分钟前
基于Spring Boot的演唱会购票系统的设计与实现(源码+文档)
java·spring boot·后端
⑩-12 分钟前
Redis内存淘汰策略?如何处理大Key?
java·数据库·redis
淡泊if14 分钟前
eBPF 实战:一次诡异的 Nginx 高延迟,我用 5 分钟在内核里找到了真凶
java·运维·nginx·微服务·ebpf
栗子~~17 分钟前
hardhat 单元测试时如何观察gas消耗情况
开发语言·单元测试·区块链·智能合约
The hopes of the whole village19 分钟前
Matlab FFT分析
开发语言·matlab
李白的粉23 分钟前
基于springboot的桂林旅游景点导游平台
java·spring boot·毕业设计·课程设计·源代码·桂林旅游景点导游平台
兰文彬27 分钟前
n8n 2.x版本没有内嵌Python环境
开发语言·python
yiyaozjk30 分钟前
Go基础之环境搭建
开发语言·后端·golang