C++学习——类型转换

不是必要操作,就不要经常使用类型转换

静态转换(static_cast)

用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换

  • 进行上行转换(把派生类的指针或引用转换成基类表示)是安全
  • 进行下行转换(把基类指针或引用转换成派生类表示)时,由于没有动态类型检查,所以是不安全的
//父子之间的转换
class Base{};
class Child : public Base {};
class Other {};

void test02()
{
	Base *base = NULL;
	Child *child = NULL;
	//向下转换   不安全
	Child *child2 = static_cast<Child*>(base);
	//向上转换   安全
	Base *base2 = static_cast<Base*>(child);

	//Other *other = static_cast<Other*>(base);  //类型转换无效
}

用于基本数据类型之间的转换,如把int转换成char,把char转换成int,这种转换的安全性也要开发人员来保证。

void test01()
{
	char a = 'a';
	double d = static_cast<double>(a);
	cout << "d = " << d << endl;
}

动态转换(dynamic_cast)

基本类型不可转换【因为动态转换非常严格,失去精度 或这不安全都不可以转换】

在进行向下转换的时候,如果发生了多态,那么可以让基类转换为派生类,是安全的

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

void test02()
{
	Base *base = NULL;
	Child *child = NULL;
	//向下转换   不安全
	//Child *child2 = dynamic_cast<Child*>(base);
    //发生多态后,可以向下转换  安全
	Base *base3 = new Child;
	Child *child3 = dynamic_cast<Child*>(base3);
	//向上转换   安全
	Base *base2 = dynamic_cast<Base*>(child);

	//Other *other = dynamic_cast<Other*>(base);  //类型转换无效
}

常量转换(const_cast)

不能直接对非指针或非引用的变量使用const_cast 操作符去移除它的const

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

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

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

	//不能对非指针  或 非引用的 变量进行转换
	//const int a = 10;  //直接放符号表了
	//int b = const_cast<int>(a)
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值