<七>C++的四种类型转换

C语言中我们使用 int a=(int) b;的方式强制转换

C++提供了四种类型转换方式

const_cast

把常量属性去掉的一个转换.
const int a =10;
int *p1=(int *)(&a);//C 语言 OK
int *p2=const_cast<int *>(&a);//OK
double *p3 =(double *) (&a)//c 语言中可以,p3的寻址范围变大,带来风险
double *p4=const_cast<double *>(&a);//c++在编译阶段就提示错误
只用于去掉常量属性的地方
int b=const_cast<int>(a);//NO ,ERROR const_carst<这里必须是指针或者引用>

static_cast

能够提供编译器认为安全的类型转换
90%使用场景是这个,这个用的是比较多的,几乎能做任何类型转换,但是是要译器认为安全的类型转换
int a=10;
char b=static_cast<int>(a);//OK
int *p=nullptr;
short *b=static_cast<short *>(p) ; //c++ NO , 两者之间没有任何联系
double *b=static_cast<double *>(p) ;//C++ NO , 两者之间没有任何联系
double *b1=(double *)(p) ;//C语言 OK 
基类和派生类之间可以使用 static_cast 

reinterpret_cast

int *p=nullptr;
short *b=reinterpret_cast<short *>(p) ; //c++ OK ,
double *b=reinterpret_cast<double *>(p) ;//C++ OK , 
double *b1=(double *)(p) ;//C语言 OK 
类似于C语言的强制类型转换

dynamic_cast
主要用着继承结构中,可以支持RTTI类型识别的上下转换

代码

#include <iostream>
using namespace std;
class A{
public:
 
 void virtual function(){
	
	cout<<"A function()"<<endl;
	
 }
};
class B : public A{
public:
 void virtual function(){	
	cout<<"B function()"<<endl;
	
 }
	
 void virtual test(){	
	cout<<"B function()"<<endl;
	
 }
};
class C : public A{
public:
 void virtual function(){
	
	cout<<"C function()"<<endl;
	
 }
};
class D : public A{
public:
 void virtual function(){	
	cout<<"D function()"<<endl;	
 }
};
void show(A * pa){
 //dynamic_cast 会检查p指针是否指向的是一个B对象
 //pb->vfptr->vftable ->RTTI信息,如果dynamic_cast转换成功
 //返回 指向B的地址,否则返回nullptr
 B *pb =dynamic_cast<B *> pa;
 if(pb!=nullptr){
	 pb->test();
 }
 else{
	 pa->function();
 }
}
int main(){
 B b;
 C c;
 D d;
 show(&b);
 show(&c);
 show(&d);
 return 0; 
 
}
作者:Hello_Bugs原文地址:https://www.cnblogs.com/erichome/p/16936877.html

%s 个评论

要回复文章请先登录注册