1.static_cast(编译时进行类型检查)
static_cast < type-id > ( expression ) 将expression转换为type-id类型 但没有在运行时检查来保证转换的安全性
用法:
- 用于基本数据类型之间的转换
- 把空指针转换成目标类型
- 把任意类型转换成空类型
- 用于类层次结构中的父类和子类之间的指针和引用类型转换
#include<iostream>
using namespace std;
class Date{
public:
void fun()
{
cout<<"Date......"<<endl;
}
};
class Son:public Date{
public:
void fun()
{
cout<<"Son..........."<<endl;
}
};
int main()
{
char a='A';
int b=static_cast<int>(a);//基本数据类型转换
cout<<b<<endl;
//将空指针转换成目标类型
void *p=static_cast<void*>(&a);
int *pd=static_cast<int*>(p);
cout<<*pd<<endl;
//父类的指针和引用
Date* parent=static_cast<Date*>(new Son);//向上转换
Son*child=static_cast<Son*>(new Date);//向下转换 不安全 (调用属于Son类而不是Date类的函数可能会导致访问冲突。)
为什么不安全?
用Son访问子类有父类没有的成员,就会出现访问越界的错误
return 0;
}
2.dynamic_cast关键字(运行时类型检查)
dynamic_cast主要用于类层次结构中父类和子类之间指针和引用的转换,由于具有运行时类型检查,
因此可以保证下行转换的安全性,何为安全性?
即转换成功就返回转换后的正确类型指针,如果转换失败,则返回NULL,之所以说static_cast在下行转换时不安全,是因为即使转换失败,它也不返回NULL。
上行转换同样
3.const_cast < type-id > ( expression )
const_cast运算符可用于从类中删除const、volatile和__unaligned属性。
- 常量指针被转化成非常量指针,并且仍然指向原来的对象;
- 常量引用被转换成非常量引用,并且仍然指向原来的对象;
- 常量对象被转换成非常量对象。
#include<iostream>
using namespace std;
class B{
public:
int a=10;
};
int main()
{
const B ob;
//ob.a=20;//会报错 因为ob为常对象 内容不能被修改
cout<<ob.a<<endl;
B* ob1=const_cast<B*>(&ob);
ob1->a=30;
cout<<ob1->a<<endl;
return 0;
}
reinterpret_cast < type-id > ( expression )
reinterpret_cast后的尖括号中的type-id类型必须是一个指针、引用、算术类型、函数指针或者成员指针。它可以把一个指针转换成一个整数,也可以把一个整数转换成一个指针。