类型转换基本语法

类型转换

  • 通过改变一个变量的类型为别的类型从而改变该变量的表示方式
  • 相比之下,C语言更为暴力,没有类型检查,不安全
  • C++四种风格转换操作符
static_cast基础数据类型以及具有继承关系的指针对象
dynamic_cast通常在基类与派生类之间转换时使用
const_cast主要针对const的转换
reinterpret_cast用于进行没有任何关联之间的转换,比如一个字符指针转换成一个整数类型的指针

代码:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Building {};
class Animal {};
class Cat :public Animal {};

//static_cast
void test01()
{
	int a = 97;
	char c = static_cast<char>(a);
	cout << c << endl;

	//基础数据类型的指针,转换失败
	//int* p = NULL;
	//char* sp = static_cast<char*>(p);

	//对象指针,转换失败
	//Building* building = NULL;
	//Animal* ani = static_cast<Animal*>(building);

	//转换具有继承关系的对象指针
	//父类指针转成子类指针
	Animal* anl = NULL;
	Cat* cat = static_cast<Cat*>(anl);

	//子类指针转成父类指针
	Cat* soncat = NULL;
	Animal* anifather = static_cast<Animal*>(soncat);

	Animal aniobj;
	Animal& aniref=  aniobj;

	//父类引用强制转换成子类引用
	Cat& cat1 = static_cast<Cat&>(aniref);

	//子类引用转换成父类引用
	Cat catobj;
	Cat& catref = catobj;
	Animal& anifather2 = static_cast<Animal&>(catref);

	//static_cast用于内置的数据类型
	//还有具有继承关系的指针和引用

}

 /*dynamic_cast 转换具有继承关系的指针或者引用
	 不转换基础数据类型*/
void test02()
{
	//失败,必须是指针或者引用,基础类型不能转换
	//int a = 10;
	//char c = dynamic_cast<char>(a);

	//非继承关系的指针,不能转换
	//Animal* ani1 = NULL;
	//Building* building = dynamic_cast<Building*>(ani1);


	//父类指针转换成子类指针,不安全
	//Animal* ani = NULL;
	//Cat* cat1 = dynamic_cast<Cat*>(ani);

	Cat* cat = NULL;
	Animal* ani2 = dynamic_cast<Animal*>(cat);
};


//const_cast 
void test03()
{
	//基础数据类型
	int a = 10;
	const int& b = a;
	int& c = const_cast<int&>(b);
	c = 20;
	cout << "a:" << a << endl;//20
	cout << "b:" << b << endl;//20
	cout << "c:" << c << endl;//20
	
	//看指针
	const int* p = NULL;
	int* p2 = const_cast<int*>(p);

	int* p3 = NULL;
	const int* p4 = const_cast<const int*>(p3);
	//增加或者取出变量的const性
}

//reinterpret_cast强制类型转换
typedef void(*FUNC1)(int, int);
typedef int(*FUNC2)(int, char*);
void test04()
{
	//1.无关的指针类型都可以进行转换
    Building* building = NULL;
	Animal* ani = reinterpret_cast<Animal*>(building);

	//2.函数指针转换
	FUNC1 func1;
	FUNC2 func2 = reinterpret_cast<FUNC2>(func1);
}

int main()
{
	test01();
	test03();
	return 0;
}

static_case转换小结

  • 基础数据类型可以转换
  • 基础数据类型指针不能转
  • 无关系的对象指针不能转
  • 子类指针和父类指针可以相互转换
  • 子类和父类引用可以互相转换
  • 总的来说就是用于内置数据类型和具有继承关系的指针和引用

dynamic_cast转换小结

  • 转换具有继承关系的,转换前会进行对象类型安全检查
  • 转换具有继承关系的指针和引用,无关系不能转换
  • 子类转换成父类安全,大到小可以
  • 父类转成子类不安全,小到大不可以

const_cast转换小结

  • 增加或者去除const性

reinterpret_cast转换小结

  • 任何类型都可以转换,可以转换无关类型的
  • 很暴力,转换前要清楚类型,不安全
  • 一般情况不建议这么转换
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr_Csyn

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

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

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

打赏作者

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

抵扣说明:

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

余额充值