[C++]类型转换

类型转换的含义是通过改变一个变量的类型为别的类型从而该变量的表示方式。

C风格的强制类型转换

Type b=(Type)a;

简单却不安全,并没有做类型检查


C++风格的类型转换提供了4种类型转换操作符来应对不同场合的的应用

static_cast 一般的类型转换(内嵌的类型:int,float…以及具有亲子类关系的类型转换:转为子类或父类等)
dynamic_cast 通常在基类和派生类之间转换使用(会进行安全检查)
const_cast 主要针对const的转换
reinterpret_cast 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整型数
#include<iostream>
using namespace std;

class Building {};
class Animal {};
class Cat :public Animal {};
//测试static_cast的用法
void text1() {
	//转换基础数据类型
	int a = 97;
	char b = static_cast<char> (a);
	cout <<"text1: b = "<< b << endl;
	//转换为对应的ASCII码值

	//只能转换具有继承关系的指针,即不能转为Building类型
	Animal* animal = NULL;
	Cat* cat1 = static_cast<Cat*> (animal);

	//具有继承关系的引用之间进行转换
	Animal ani;
	Animal& aniref = ani;
	Cat& catref = static_cast<Cat&> (aniref);
}


/*
dynamic_cast动态类型转换
只能转换具有继承关系的指针或引用,但在转换前会进行对象数据类型的检查
子类指针可以转换为父类指针(包含内容从大变小)
由于父类指针转换成子类指针可能会涉及父类所不具有的属性与方法
并不安全,所以dynamic_cast在进行安全检查时会拒绝这种转换
*/

void text2() {
	Cat* cat1 = NULL;
	Animal* ani = dynamic_cast<Animal*> (cat1);
}

//测试const_cast的用法
//针对指针,引用或者对象指针
//主要用来增加或者去除变量的const属性
void text3() {
	//引用部分
	int a = 10;
	const int& b = a;
	//b由const修饰不能进行修改
	int&c=const_cast<int&>(b);
	//经过类型转换c是整型引用,可以进行修改
	cout << "text3:c修改前:a= " << a << " b = " << b << " c = " << c << endl;
	c = 25;
	cout << "text3:c修改前:a= " << a << " b = " << b << " c = " << c << endl;
	//指针部分
	const int* p = NULL;
	int *p2=const_cast<int*>(p);
	int* p2 = NULL;
}

//测试reinterpret_cast的用法
//强制类型转换,用于进行没有任何关联之间的转换
void text4() {
	//无关的指针都可以进行转换
	Building* build = NULL;
	Animal* ani = reinterpret_cast<Animal*>(build);

}
int main() {
	text1();
	text3();
	return 0;
}

一般情况下不建议进行类型转换,如果过需要进行类型转换,程序员必须清楚变量转换前是什么数据类型,转换后又是什么类型。

发布了18 篇原创文章 · 获赞 2 · 访问量 240

猜你喜欢

转载自blog.csdn.net/renboyu010214/article/details/104416786