C++基础——类型转换篇

c++类型转换函数

在C++中,进行类型转换的函数可以有很多种,以下是几种常见的类型转换方法:

使用C++的static_cast进行类型转换:

int i = 10;
double d = static_cast<double>(i);

使用C++的dynamic_cast进行类型转换,这主要用于类层次结构中的上下转换:

class Base { virtual void dummy() {} };
class Derived : public Base { /* ... */ };
Base* ptr = new Derived;
Derived* dptr = dynamic_cast<Derived*>(ptr);

使用C++的const_cast去除变量的const属性:

const int i = 10;
int* p = const_cast<int*>(&i);

使用C++的reinterpret_cast进行不安全的类型转换:


int* p = new int(65);
char* c = reinterpret_cast<char*>(p);

使用函数模板进行类型转换:

template <class T, class U>
T convert(U u) {
    return static_cast<T>(u);
}
 
int i = convert<int>(3.14);

使用C++11标准中的std::function和std::bind进行类型转换:

#include <functional>
 
void print(int i) {
    std::cout << i << std::endl;
}
 
std::function<void(int)> func = print;
func(5);
  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值