C++四种强制类型转换

本文详细介绍了C++中的四种类型转换:static_cast、dynamic_cast、const_cast和reinterpret_cast。包括它们的基本用法、适用场景及注意事项,特别是dynamic_cast在继承体系中的应用。

四种强制类型转换:

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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值