C++类型转换
类型转换(cast)是将一种数据类型转换成另一种数据类型
转换是非常有用的,但是它也会带来一些问题,比如在转换指针时,我们很可能将其转换成一个比它更大的类型,但这可能会破坏其他的数据。
C++风格的强制转换其他的好处是,它们能更清晰的表明它们要干什么。程序员只要扫一眼这样的代码,就能立即知道一个强制转换的目的。
1 静态转换(static_cast)
1> 用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
2> 用于基本数据类型之间的转换,如把int转换成char,把char转换成int。这种转换的安全性也要开发人员来保证。
2 动态转换(dynamic_cast)
1> ynamic_cast主要用于类层次间的上行转换和下行转换;
2>在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;3>在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全;
3 常量转换(const_cast)
该运算符用来修改类型的const属性
1> 常量指针被转化成非常量指针,并且仍然指向原来的对象;
2> 常量引用被转换成非常量引用,并且仍然指向原来的对象;
注意:不能直接对非指针和非引用的变量使用const_cast操作符去直接移除它的const.
4 重新解释转换(reinterpret_cast)
这是最不安全的一种转换机制,最有可能出问题。
主要用于将一种数据类型从一种类型转换为另一种类型。它可以将一个指针转换成一个整数,也可以将一个整数转换成一个指针.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//1. static_cast具有继承关系的指针或者引用向上或者向下类型转换
//内置的基础数据类型转换
class Base01{};
class Derived01 : public Base01{};
class Other{};
void test01(){
//1.转换指针或者引用
Base01* b = NULL;
Derived01* d = NULL;
//<Derived01*> 要转换的目标类型
//(b) 把谁转换成目标类型
Derived01* nd = static_cast<Derived01*>(b); //向下类型转换,不安全的转换
Base01* nb = static_cast<Base01*>(d); //向上类型转换,安全
//Other* o = static_cast<Other*>(b); 不能转换非继承关系的指针或者引用
//2.转换基础数据类型
int a = 10;
char c = static_cast<char>(a);
}
//2. dynamic_cast 动态类型转换,用于具有继承关系的指针或者引用向上转换
void test02(){
Base01* b = NULL;
Derived01* d = NULL;
//向上类型转换
Base01* nb = dynamic_cast<Base01*>(d);
//向下类型转换
//Derived01* nd = dynamic_cast<Derived01*>(b);
}
//3. const_cast
void test03(){
const int* p = NULL;
int* np = const_cast<int*>(p);
int* pp = NULL;
const int* npp = const_cast<const int*>(pp);
const int a = 10;
//int b = const_cast<int>(a);
}
//4. reinterpret_cast 强制类型转换,最不安全的
void test04(){
int a = 10;
int* p = reinterpret_cast<int*>(a);
Base01* b = NULL;
Other* o = reinterpret_cast<Other*>(b);
}
//尽量不要用,不要进行类型转换
int main(){
system("pause");
return EXIT_SUCCESS;
}