c++中类型转换

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Building
{

};

class animal
{
	virtual void nihao() = 0;
};
class cat :public animal
{
	void nihao()
	{
		cout << "你好" << endl;
	}
};
typedef void (fun)(int a, int b);
typedef int(fun2)(int c, char *);

int main()
{
	#if 0
	int a = 65;
	char b = static_cast<char>(a);//将a转化为char类型
	cout << b << endl;
	animal* abc = NULL;
	//父类指针转化为子类指针
	cat* cd = static_cast<cat*>(abc);

	//子类指针转为父类指针
	cat* CAT = NULL;
	animal *catfather = static_cast<animal*>(CAT);
	animal aniobj;
	animal &anir = aniobj;
	cat& CAT = static_cast<cat&>(anir);
	//static_cast 用于内置的数据类型
	//还要具有继承关系的指针或者引用
#endif

#if 0
	animal* c = NULL;
	c = new cat();
	//子类一般都要大于等于父类
	/*子类转为父类 从大变小安全 但是从小变为大 会出现地址越界不安全*/
	cat* ccc = dynamic_cast<cat*>(c);//必须包含多态数据类型
	/* 转化具有继承关系的指针或者引用
		
		在转换前会进行对象的检查*/
	cat* Cat = NULL;
	animal* an = dynamic_cast<animal*>(Cat);
	dynamic 只能子类转换为基类 大转小即可
#endif

#if 0
	int a = 10;
	const int& b = a;
	//b 引用 a c引用b c修改了 三个变量共享一份内存空间
	// 
	//b =10
	int &c = const_cast<int&>(b);
	c = 20;
	cout << a << "  " << b << "  " << c << endl;//20 20 20

	const int* p = NULL;
	int* bb = const_cast<int*>(p);//把p抓为int *
	int* p3 = NULL;
	const int* p4 = const_cast<const int*>(p3);//把p3转为const int *
	//const增加或者去除变量的const性
#endif
	Building* abc = NULL;
	animal* nimal =reinterpret_cast<animal*>(abc);//强制类型转换 任何指针的转换 -----强制转换
	fun* FUN1 = NULL;;
	fun2 *FUN2 = reinterpret_cast<fun2*>(FUN1);

}

/*

static_cast  一般的转换
dynamic_cast 基类和派生类之间的转换
const_cast 主要针对const的转换
reinterpret_cast 没有任何关联的转换
*/

程序员必须清楚的知道要转变的变量 ,转换前是什么类型 以及转换后有什么后果
一般建议不要类型转换

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值