c++中的四种类型转换

在c++当中强制类型转换分为4种,他们都以cast结尾。
使用方法:强制类型转换名(express)

一:static_cast属于静态转换,编译时就会进行类型转换的检查。

#include <iostream>
#include <string>
using namespace std;
	
class A
{
public:
};

class B :public A
{
public:
};

int main()
{
	/*double转int*/
	double f = 100.34f;
	int i = static_cast<int>(f);

	/*子类转父类*/
	B obj2;
	A obj1 = static_cast<A>(obj2);

	/*void*与其它的指针类型转换*/
	int x = 10;
	int* p = &x;
	void* q = static_cast<void*>(p);
	int* pq = static_cast<int*>(q);


	double f2 = 100.0;
	double* pf = &f2;
	//int* u = static_cast<int*>(pf);无效
}

二:dynamic_cast,在运行时期进行的类型识别和检查。主要用来进行父类转成子类类型。

三:const_cast去除指针或者引用的const属性,编译时的类型转换检查

#include <iostream>
#include <string>
using namespace std;
	
int main()
{
	const int ci = 90;
	//int ci2 = const_cast<int>(ci); //不是指针和引用,错误
	const int* pai = &ci;
	int* pai2 = const_cast<int*>(pai);
	*pai2 = 30; //不要这么干,实际上这里还是const
	cout << ci << endl;//90
	cout << *pai << endl;//30
	cout << *pai2 << endl;//30
}

四:reinterpret_cast属于编译时的类型转换检查。一般是怎么转都可以,但是存在危险,比如int转string等。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酸菜。

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值