概念
类型转换的含义是通过改变一个变量的类型为别的类型从而改变该变量的表示方式。为了类型转换一个简单对象为另一个对象你会使用类型转换操作符。
C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:TYPE b = (TYPE)a
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
类型 | 用法 |
---|---|
static_cast | 一般的转换 |
dynami_cast | 通常在基类和派生类之间转换时使用 |
const_cast | 主要针对const的转换 |
reinterpert_cast | 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整型数 |
代码:
#include<iostream>
using namespace std;
class Building{};
class Animal{};
class Cat :public Animal{};
//static_cast
void test01(){
int a = 97;
char c = static_cast<char>(a);
cout << "c = " << c << endl;//输出ASCII值 a
//基础数据类型的指针
int *p = NULL;
//char* sp = static_cast<char*>(p);//error
//对象指针
Building* building = NULL;
//Animal* ani = static_cast<Animal*>(building);//error
//转换具有继承关系的对象指针
//父类指针转子类指针
Animal* ani = NULL;
Cat* cat = static_cast<Cat*>(ani);//ok
//子类指针转换为父类指针
Cat* soncat = NULL;
Animal* anifather = static_cast<Animal*>(soncat);//ok
Animal aniobj;
Animal& aniref = aniobj;
Cat& cat2 = static_cast<Cat&>(aniref);//ok
Cat catobj;
Cat& catref = catobj;
Animal& anifather2 = static_cast<Animal&>(catref);//ok
/*static_cast 用于内置的数据类型,
还有具有继承关系的指针或引用*/
}
//dynamic_cast 转换具有继承关系的指针或引用,在转换前会进行对象类型检查
void test02()
{
//基础数据类型 不能转换
int a = 10;;
//char c = dynamic_cast<char>(a);//error
//非继承关系的指针
Animal* ani = NULL;
//Building* building = dynamic_cast<Building*>(ani);//error
//具有继承关系指针
//Animal* ani = NULL;
//Cat* cat = dynamic_cast<Cat*>(ani);//error
/*原因在于 dynamic_cast做类型安全检查
子类指针可以转换为父类指针(从大到小),类型安全,因为,子类包含父类的元素,指针作用域大,不会指针越界
父类指针转换成子类指针(从小到达),类型不安全,会发生指针越界*/
Cat* cat = NULL;
Animal* ani2 = dynamic_cast<Animal*>(cat);
/*结论:
dynamic_cast只能转换具有继承关系的指针或者引用,并且
只能由子类型转换为基类型*/
}
//const_cast 指针 引用或者对象指针
void test03()
{
//1 基础数据类型
int a = 10;
const int& b = a;
//b=10;//error 无法改变
int& c = const_cast<int&>(b);//const属性取消
c = 20;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
cout << "c:" << c << endl;
/*输出:
a:20
b:20
c:20
*/
//指针
const int* p = NULL;
int* p2 = const_cast<int*>(p);//OK
int* p3 = NULL;
const int* p4 = const_cast<const int*>(p3);//增加const属性
/*结论:
增加或者去除变量的const属性*/
}
//reinterpret_cast 强制类型转换 无关的指针类型,包括函数指针都可以
typedef void(*FUNC1)(int, int);
typedef int(*FUNC2)(int, char*);
void test04()
{
//1. 无关的指针类型都可以进行转换
Building* building = NULL;
Animal* ani = reinterpret_cast<Animal*>(building);
//2. 函数指针转换
FUNC1 func1;
FUNC2 func2 = reinterpret_cast<FUNC2>(func1);
}
/*总结
结论1:程序员必须清楚的知道要转变的变量,转换前是什么类型,转换后是什么类型,以及
转换后有什么结果
结论2:一般情况下,不建议类型转换,避免进行类型转换*/
int main()
{
cout<<"hello world"<<endl;
test01();
test03();
return 0;
}
总结
结论1:程序员必须清楚的知道要转变的变量,转换前是什么类型,转换后是什么类型,以及
转换后有什么结果;
结论2:一般情况下,不建议类型转换,避免进行类型转换;