首页 > 其他 > 详细

类型转换

时间:2021-05-30 20:15:53      阅读:16      评论:0      收藏:0      [点我收藏+]

静态类型转换

可以进行转换的有(基础数据类型,父与子关系)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//静态转换static_cast<目标>(原始数据)
//基础数据类型转换
void test01()
{
	char a = ‘a‘;
	double d = static_cast<double>(a);
	cout << "d = " << d << endl;
}
//父子之间转换
class Base {};
class Child :public Base {};
class Othre {};
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);
}
int main()
{
	test01();
	test02();
	return 0;
}

动态类型转换

可以进行转换的有(不可以转换基础数据类型,父类转换子类不行,子类转父类可以,发生多态都可以)

//父子之间转换
class Base {
	virtual void func() {};
};
class Child :public Base {
	virtual void func() {}
};
class Othre {};
//动态类型转换
void test03()
{
	//基础类型不可以转换
	char c = ‘a‘;
	//失去精度,或者不安全都不可以转换
	//double d = dynamic_cast<double>(c);
	Base* b1 = NULL;
	Child* c1 = NULL;
	Othre* o1 = NULL;
	Base* b2 = dynamic_cast<Base*>(c1);
	//Child* c2 = dynamic_cast<Child*>(b1);
	//Child* c3 = dynamic_cast<Child*>(b2);
	Base* b3 = new Child;
	Child* c3 = dynamic_cast<Child*>(b3);
}

常量转换

常量转换(const_cast) 不能对非指针 或者非引用的变量进行转换

//常量转换(const_cast)
void test01()
{
	const int *p = NULL;
	//取出const
	int* newp = const_cast<int *>(p);
	int* p2 = NULL;
	//加上const
	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 = const_cast<const int&>(numRef);
}

类型转换

原文:https://www.cnblogs.com/lodger47/p/14828582.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!