C++类型转换:static_cast、const_cast、dynamic_cast、reinterpret_cast

C++类型转换包括4种:static_cast、const_cast、dynamic_cast、reinterpret_cast这四种。

 

类型转换的问题常常遇到。找工作的时候,网易游戏的提前批面试问到了,百度的客户端研发笔试题也考到了。其实,不看的话绝对不知道。


static_cast:
1、静态类型转换。比如,可以将int类型的变量转换为char类型的变量。
2、可以将空指针转换为目标类型的指针。
3、可以将任何类型转化为void类型。

const_cast:
1、去掉const特性。

dynamic_cast:
1、可以将基类类型对象的引用或指针转换为同一继承层次中其他类型的引用或指针。 
2、需要有虚函数,方可保证运行时类型识别(RTTI)可以生效。

通过运行时类型识别(RTTI),程序能够使用基类的指针或引用来检索这些指针或引用所指对象的实际派生类型。通过dynamic_cast操作符可以提供RTTI。dynamic_cast操作符可以将基类类型的指针或引用安全地转换为派生类型的指针或引用。是由于运行时类型检查需要运行时类型信息,而这个信息存储在类的虚函数表(关于虚函数表的概念,详细可见<Inside c++ object model>)中,只有定义了虚函数的类才有虚函数表。
3、如果运行时,实际绑定的对象不是目标(转换后)类型的对象(或其派生类的对象),则dynamic_cast失败。

reinterpret_cast:
1、可以在函数指针类型之间进行转换。
2、可移植性差。

 

以下是代码:

class Widget
{
public:
	int a;
	virtual void dosomething(){}
};

class SpecialWidget:public Widget
{
public:
	float b;
};

void update(SpecialWidget* psw)
{
	printf("successful call");
}

int doonething()
{
	return 1;
}
int main(int argc, char* argv[])
{
	int x1 = 5; double x2 = 1.1;
	double result = static_cast<double>(x1)/x2;  // static_cast
	printf("result = %f\n",result);

	SpecialWidget sw;
	const SpecialWidget& csw = sw;
	update(const_cast<SpecialWidget*>(&csw));    // const_cast

	Widget* pw = new SpecialWidget();
	update(dynamic_cast<SpecialWidget*>(pw));    // dynamic_cast

	typedef void (*FuncPtr)();
	FuncPtr funcPtrArray[10];
	int doonething();
	funcPtrArray[0] = reinterpret_cast<FuncPtr>(doonething);  // reinterpret_cast


	printf("Hello World!\n");
	return 0;
}

第一次运行上面的代码时,我的VS编译器报错。

错误信息:warning C4541: 'dynamic_cast' used on polymorphic type 'class CWnd' with /GR-; unpredictable behavior may result

其实原因:没有打开run-time   type   information   支持就使用'dynamic_cast'    

打开的方法:菜单project-setting-c/c++  c++   language - enable   run-time   type   information   (RTTI)  


 关于C++类型转换,有个人写的很不错。

http://www.cnblogs.com/goodhacker/archive/2011/07/20/2111996.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值