四种强制类型转换:
static_cast const_cast dynamic_cast reinterpret_cast
1、static_cast 完成编译器认可的隐式类型转换
例如:
int a=10;
double b=static_cast<double>(a);
cout<<b<<endl;
注:用于C++内置类型的转换,不能用于不相关类型之间的转换
例如: int *p=static_cast<int *>(a);//a是int 类型
2、dynamic_cast 执行派生类指针或引用与基类指针或引用之间的转换
1、其他三种都是编译时完成的,dynamic_cast是运行时处理的,运行时 要进行类型检查
2、基类中要有虚函数,因为运行时检查的类型信息在虚函数表中,有虚函数才会有虚函数表
3、dynamic在进行转换时先会检查是否会转换成功,能成功则转,不成功就会返回0
class Base
{
public:
Base()
{
cout<<"Base()"<<endl;
}
virtual void f()
{
cout<<"Base::f()"<<endl;
}
~Base()
{
cout<<"~Base()"<<endl;
}
};
class Derive:public Base
{
public:
Derive()
{
cout<<"Derive"<<endl;
}
void f()
{
cout<<"Derive::f()"<<endl;
}
~Derive(){
cout<<"~Derive"<<endl;
}
};
使用dynamic_cast转换:
Base *a1=new Derive();
Base *a2=new Base();
Derive *b;
b=dynamic_cast<Derive*>(a1);
if(b==NULL) {cout<<"NULL"<<endl;}
else {cout<<"ok"<<endl;}
//但是下面的就不可以转换了
b=dynamic_cast<Derive*>(a2);
if(b==NULL) {cout<<"NULL"<<endl;}
else {cout<<"ok"<<endl;}
3、const_cast :只能对指针或者引用去除或者添加const属性,对于变量直接类型不能使用const类型转换,不能用于不同类型之间的转换,只能用于同类型之间的转换
const int a=30;
const int *p=&a;
int *q;
q=const_cast<int *>(p);
*q=10;
cout<<a<<*p<<*q<<endl
4、reinterpret_cast: 重新解释的类型转换,对于任意两个类型之间的转换,我们都可以用reinterpret_cast ,无视类型信息
int *a=new int;
double *d=reinterpret_cast<double*>(a);