zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ 类型强转

C++ 类型
2023-09-11 14:13:59 时间

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