C++的类型转换

隐式类型转换

比如 double f1.0/2;
比如:
couble f=10.2

显式类型转换

(类型说明符)(表达)
比如: double f=double(1)/double(2);

C类型转换的问题

  1. 任意类型之间都可以转换,编译器无法判断其正确性
  2. 难与定位,在源代码中无法快速单位

C++的类型转换.

const_cast

用于转换指针或引用,去掉类型的const属性
int main()
{
	const int a = 10;
	//int* pA = &a;
	int* pA=const_cast<int*>(&a)
	*pA=100;
	return 0;
}

reinterpret_cast

很危险!
重新解释类型,既不检查指向的内容,也不检查指针类型本身 ;但要求转换前后的类型所占用内存大小一致,否则将引发编译时错误…

int Test(){
	return 0;
}
int main()
{
typedef void(*FuncPtr)();
FuncPtr funcPtr;
//funcPtr=&Test;
funcPtr=reinterpret_cast<FuncPtr>(&Test);
}

static_cast

用于基本类型转换,有继承关系类对象和类指针之间转换,由程序员来确保转换是安全的,它不会产生动态转换的类型安全检查的开销

int i = 5;
double d= static_cast<double>(i);
double d2 = 5.6;
int i2 = static_cast<int>(d2);

dynamic_cast

只能用于含有虚函数的类,必须用在多态体系中,用于类层次间的向上和向下转化.向下转化时,如果是非法的对于指针返回NULL

class Base
{
public
	Base():_i(0){}
	virtual void T(){cout<<"Base:T"<<_i<<endl;}
private
	int _i;
}

class Derived:public Base
{
public:
	Derived:_j(1) (;)
	virtual void T(){cout<<"Derived:T"<<_i<<endl;}
private:
	int _j;
}

int main(){
	Base cb;
	Derived cd;
	Base* pcb;
	Derived* pcd;
	//子类->父类
	pcb = static_cast<Base*>(&cd)
	pcb = dynamic_cast<Base*>(&cd)
	if(pcb == NULL){
		cout<<"unsafe dynamic_cast from Derived to Base"<<endl;
	}
	//父类->子类
	pcd = static_cast<Derived*>(&cb)
	pcd = dynamic_cast<Derived*>(&cb)
	if(pcd == NULL){
		cout<<"unsafe dynamic_cast from Base to Derived "<<endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值