c++中的四种类型转换

c++中的四种类型转换

#include <iostream>
//using namaspace std;
//C++中的四种类型转换

class A
{
public:
	
	virtual void fn()
	{

	}
private:

};
class B:public A
{
public:
	void fn()
	{

	}

private:

};
class C
{
public:

	 void fn()
	{

	}
private:

};
class D :public C
{
public:
	void fn()
	{

	}

private:

};


int _tmain(int argc, _TCHAR* argv[])
{

	//  static_cast   用于基本类型之间的类型转换 

	float x = 10.3;
	int y;
	y = static_cast<int>(x);


	//  const_cast    用于常量类型转换 把const类型的指针或者引用转换为非const类型
	int k = 5;
	int const *const_x = &k;
	int *noconst_x = const_cast<int*>(const_x);

	//reinterpret_cast  重新解释类型转换,此标识符的意思即为数据的二进制形式重新解释,但是不改变其值。一般不常用
	
    int i; 
	char *ptr="aaaa";
	i=reinterpret_cast<int>(ptr);

	//dynamic_cast 动态类型的转换该操作符用于运行时检查该转换是否类型安全,但只在多态类型时合法,
	//dynamic_cast与static_cast具有相同的基本语法,static_cast转换的时候没有类型检查,因而不安全
	

	dynamic_cast<A*> (new B);
	dynamic_cast<B*> (new A);


	dynamic_cast<C*> (new D);
	dynamic_cast<D*> (new C);//类型检查错误


	static_cast<A*> (new B);
	static_cast<B*> (new A);


	static_cast<C*> (new D);
	static_cast<D*> (new C);


	
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值