设为首页 加入收藏

TOP

<十>C++的四种类型转换
2023-07-23 13:35:30 】 浏览:26
Tags:< >

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

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

const_cast


通过const_cast运算符,也只能将const type转换为type,将const type&转换为type&。
也就是说源类型和目标类型除了const属性不同,其他地方完全相同


把常量属性去掉的一个转换.
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; 
        
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇<一>智能指针之__智能指针.. 下一篇noi 1.5 39 与7无关的数

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目