C++ 类型强转


class A {};
class B : public A {};

int main()
{
	// static_cast:在编译期间完成类型转换
	float f_a = 1.123456; 
	cout << "f_a = " << f_a << endl;
	int i_a = static_cast<int>(f_a); 
	cout << "i_a = " << i_a << endl;
	
	void* vp_a = "123456"; 
	cout << "(char*)vp_a = " << (char*)vp_a << endl;
	char* cp_a = static_cast<char*>(vp_a);
	cout << "cp_a = " << cp_a << endl;

	// const_cast:用于 const 转 非const,且<>中只能是指针或引用
	const int ci_a = 1;
	int* pi_a = const_cast<int*>(&ci_a);
	*pi_a = 10;
	cout << "ci_a = " << ci_a << endl;
	cout << "*pi_a = " << *pi_a << endl;
	
	// reinterpret_cast:直接修改二进制,功能强大但风险也大。比如下面代码使用 static_cast 就会出错,但 reinterpret_cast 就可以编译成功
	int* pi_b;
	double* pd_a = reinterpret_cast<double*>(pi_b);

	// dynamic_cast:用于类的转换
	B* b;
	A* a;
	a = dynamic_cast<A*>(b);
	//b = dynamic_cast<B*>(a);	// 错误,只支持子类转父类

	
	getchar();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值