#include "stdafx.h"
using namespace std;
/**
C语言类型转换
隐式类型转换:
double f = 1.0/2;
显示类型转换:
类型说明符(表达式)
比如: double f = double(1)/double(2);
C 语言类型转换的问题:
1. 任意类型之间都可以转换,编译器无法判断其正确性;
2. 难于定位:在源码中无法快速定位
C++的类型转换
const_cast
用于转换指针或引用,去掉类型的const属性
reinterpret_cast 很危险
重新解释类型,既不检查指向的内容,也不检查指针类型本身,
但要求转换前后的类型所占的内存大小一致,否则将引发编译时错误。
static_cast
用于基本类型转换,有继承关系类对象和指针之间转换,确保转换是安全的,
它不会产生动态转换的类型安全检查的开销。
dynamic_cast
只用用于含有虚函数的类,必须用在多态体系中,用于类层次间的向上和向下转化,
向下转化时,如果是非法的对于指针返回NULL;
向上转化: 鸭子转成动物
向下转化: 动物转成鸭子
*/
class Base
{
public:
Base():_i(0){
}
virtual void T(){
cout<<"Base T "<<_i<<endl;
}
private:
int _i;
};
class Derived:public Base
{
public:
Derived():_j(0){
}
virtual void T() override{
cout<<"Derived T "<<_j<<endl;
}
private:
int _j;
};
int doSomeThings(){
cout<<"doSomethings"<<endl;
return 0;
}
int main(int argc, const char * argv[]) {
// C++ const转换
const int a = 10;
//int* pA= &a;
int* pA = const_cast<int*>(&a);
*pA = 20;
cout<<*pA<<endl;
// C++ reinterpret_cast
typedef void(*FuncPtr)();
FuncPtr funcPtr;
funcPtr = reinterpret_cast<FuncPtr>(&doSomeThings);
funcPtr();
//static_cast dynamic_cast
int i= 5;
double d = static_cast<double>(i);
cout<<d<<endl;
Base ca;
Derived ce;
Base* pCa;
Derived* pCe;
// 子类转父类
pCa = static_cast<Base*>(&ce);
if (pCa == NULL){
cout<<"unsafe dynamic_cast from Derived to Base 1"<<endl;
}
pCa->T();
pCa = dynamic_cast<Base*>(&ce);
if (pCa == NULL){
cout<<"unsafe dynamic_cast from Derived to Base 2"<<endl;
}
pCa->T();
// 父类转子类
pCe = static_cast<Derived*>(&ca);
pCe->T();
if (pCe == NULL){
cout<<"unsafe dynamic_cast from Derived to Base 3"<<endl;
}
// 父类转换成子类时 为NULL
pCe = dynamic_cast<Derived*>(&ca);
if (pCe == NULL){
cout<<"unsafe dynamic_cast from Derived to Base 4"<<endl;
}
//pCe->T();
return 0;
}
输出如下:
20
doSomethings
5
Derived T 0
Derived T 0
Base T 0
unsafe dynamic_cast from Derived to Base 4