C++类型转换

       

       类型转换(cast)是将一种数据类型转换成另一种数据类型。例如,如果将一个整型值赋给一个浮点类型的变量,编译器会暗地里将其转换成浮点类型。

       应该小心类型转换,因为转换也就相当于对编译器说:忘记类型检查,把它看做其他的类型。

       一般情况下,尽量少的去使用类型转换,除非用来解决非常特殊的问题。

静态转换(static_cast)

静态转换 static_cast

  • 使用方式  static_cast< 目标类型>(原始数据)
  • 可以进行基础数据类型转换
  • 父与子类型转换
  • 没有父子关系的自定义类型不可以转换

动态转换 dynamic_cast

  • 不可以转换基础数据类型
  • 父子之间可以转换
  •      父转子 不可以
  •      子转父 可以
  • 发生多态 都可以

常量转换 const_cast

  • 不能对非指针或者非引用进行转换

重新解释转换 reinterpret_cast

  • 最不安全,最鸡肋 不推荐
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

//静态转换
//基础类型

void test01()
{
	char a = 'a';

	double d = static_cast<double>(a);

	cout << "d=" << d << endl;
}

//父子之间的转换
class Base{};
class Child :public Base{};
class Other{};

void test02()
{
	Base *base = NULL;
	Child *child = NULL;

	//把Base转为Child*类型 向下 不安全
	Child *child2 = static_cast<Child*>(base);

	//把Child转为Base类型 向上  安全
	Base *base2 = static_cast<Base*>(child);

	//转Other
	//Other *other = static_cast<Other*>(base);  无效,没有父子关系
}

//static_cats使用  static_cats<目标类型>(原始对象)


//动态转换
void test03()
{
	//基础类型不可以转换
	char c = 'a';
	//非常严格,失去精度 或者不安全都不可以转换
	//double = dynamic_cast<double>(c);
}

class Base2
{
	virtual void func(){};
};
class Child2 :public Base2
{
	virtual void func(){};
};
class Other2{};

void test04()
{
	Base2 *base = NULL;
	Child2 *child = NULL;

	//child转Base2 *  安全
	Base2 *base2 = dynamic_cast<Base2*>(child);

	//Base转child* 不安全
	//Child2 *child2 = dynamic_cast<Child2 *>(base);

	//发生多态情况
	Base2 *base3 = new Child2;
	Child2* child3 = dynamic_cast<Child2*>(base3);

}
//dynamic_cast 如果发生了多态,那么可以让基类转为派生类,向下转换

//常量转换

void test05()
{
	const int *p = NULL;
	//去除const
	int *newp = const_cast<int *>(p);

	int *p2 = NULL;
	const int *newp2 = const_cast<const int *>(p2);

	//不能对非指针 或 非引用的  变量进行转换
	//const int a = 10;
	//int b = const_cast<int>(a);

	//引用
	int num = 10;
	int &numRef = num;
	const int &numRef2 = static_cast<const int&>(numRef);

}

//重新解释转换
void test06()
{
	int a = 10;
	int * p = reinterpret_cast<int *>(a);

	Base *base = NULL;
	Other * other = reinterpret_cast<Other*>(base);

	//最不安全,不推荐
}

int main()
{
	test01();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值