类型转换

静态类型转换

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

#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);
}

posted on 2021-05-30 18:11  lodger47  阅读(58)  评论(0)    收藏  举报

导航