C++类型转换

C++中有4个类型转换符

static_cast

dynamic_cast

reinterpret_cast

const_cast

1、const_cast 

 const_cast(与C语言强制转换没有区别)

一般用于去除const属性,将const转换成非const

const Person* p1 = new Person;

Person* p2 = const_cast<Person *>(p1);  //C++风格
Person* p3 = (Person *)p1;  //c语言风格

2、dynamic_cast 

dynamic_cast

运行时安全检测(子类指针指向父类对象,安全检测会将指针赋值为空指针)

一般用于多态类型的转换,有运行时安全检测,不安全直接赋值为空指针

强制类型转换没有安全检测

#include <iostream>
using namespace std;

class Person 
{
public:
	int m_age;
	virtual void run() {}
};

class Student : public Person
{
public:
	int m_score;
	
};


int main()
{
	Person *p1 = new Person();
	Person *p2 = new Student();

	cout << p1 << endl;
	cout << p2 << endl;

	Student *stu1 = dynamic_cast<Student *>(p1);//不安全	
	Student *stu2 = dynamic_cast<Student *>(p2);//安全

	cout << stu1 << endl;
	cout << stu2 << endl;

	system("pause");
	return 0;
}

3、static_cast 

static_cast  等同于强制转换

对比dynamic_cast,缺乏运行时安全检测

不能交叉转换(不是同一继承体系的,无法转换)

常用于基本数据类型的转换、非const转成const,适用范围较广

4、reinterpret_cast

 reinterpret_cast

属于比较底层的强制转换,没有任何类型检查和格式转换,仅仅是简单的二进制数据拷贝

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

coder_Alger

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

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

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

打赏作者

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

抵扣说明:

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

余额充值