C++四种类型转换

简介

C++语言级别提供的四种类型转换方式,都是模板

  • const_cast:去掉(指针或引用)常量属性的类型转换,编译时期类型转换
  • static_cast: 提供编译器认为的安全的类型转换,用的最多
  • reinterpret_cast: 类似于C风格的强转
  • dynamic_cast:主要用在继承结构中,可支持RTTI类型识别的上下转换。运行时期的类型转换

const_cast

  • const_cast只能调节限定符类型,不能更改基础类型
const int a = 10;
double* p1 = (double*)&a;
int* p3 = const_cast<int*>(&a); // ok
char* p2 = const_cast<char*>(&a); // error
  • const_cast中类型只能是引用或指针类型
const int a = 10;
int b = const_cast<int>(a); //eroor

static_cast

// 基类类型 和 派生类类型可用 static_cast
int a = 10;
char b = static_cast<int>(a); // OK
int* p = nullptr;
// 如果int *转short *成功最后访问的空间本应是4B而变为1B
double* b = (double*)p; // ERROR
short* b = static_cast<short*>(p); // ERROR

reinterpret_cast

reinterpret_cast 类似于C得强制类型转换

int* p = nullptr;

double* b = reinterpret_cast<double*>(p); // OK,但不安全

dynamic_cast

关注注释

class Base
{
public:
	virtual void func() = 0;
};
class Derive1 : public Base
{
public:
	void func() { cout << "call Derive1::func" << endl; }
};

class Derive2 : public Base
{
public:
	void func() { cout << "call Derive2::func" << endl; }
	// Derive2实现新功能的API接口函数
	void derive02func()
	{
		cout << "call Derive2::derive02func" << endl;
	}
};
void showFunc(Base* p)
{
	// 实现若传给p的是 Derive2 对象就调用其 derive02func 函数
	// dynamic_cast会检查p是否指向的是 Derive2 对象
	// p->vfptr->vftable->RTTI信息,若是,dynamic_cast类型转换成功
	// 返回 Derive2对象地址给pd2,否则返回nullptr
	// dynamic_cast称为运行时期类型转换,static_cast编译时期的类型转换

	Derive2* pd2 = dynamic_cast<Derive2*>(p);
	if (pd2 != nullptr)
	{
		pd2->derive02func();
	}
	else
	{
		p->func(); // 动态绑定
	}	
	
}
int main()
{

	Derive1 d1;
	Derive2 d2;
	showFunc(&d1);
	showFunc(&d2);
	return 0;
}

输出结果

在这里插入图片描述

若将其中的dynamic_cast 替换为static_cast,则不论 Derive1 还是 Derive2 的对象都转换为Derive2*

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值