C++类型转换

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


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

//static_cast
void test01()
{
	int a = 99;
	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* ani = NULL;
	Cat* cat = static_cast<Cat*>(ani);
	//子类指针转成父类指针
	Cat* soncat = NULL;
	Animal* anifather = static_cast<Animal*>(soncat);

#if 0
	Animal aniobj;
	Animal& aniref = aniobj;
	Cat& cat = static_cast<Cat&>(aniobj);
#endif

	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* ani = NULL;
	//Building* building = dynamic_cast<Building*>(ani);

	//具有继承关系指针
	//Animal* ani = NULL;
	//Cat* cat = dynamic_cast<Cat*>(ani);
	//原因在于 dynamic做类型安全检查


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

	//结论 :dynamic只能转换具有继承关系的指针或引用
	//并且只能由子类型转换成基类型
}

//const_cast 指针 引用 或者 对象指针
void test03()
{
	//基础数据类型
	int a = 10;
	const int& b = a;
	//b = 10;
	int& c = const_cast<int&>(b);
	c = 20;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;

	//指针
	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();
	//test02();
	//test03();
	test04();

	return 0;
}


/*

结论1:程序员必须清楚的知道要转变的变量,转换前是什么类型,以及转换后有什么后果

结论2:一般情况下,不建议类型转换,避免进行类型转换

*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值