static_cast与reinterpret_cast

static_cast与reinterpret_cast

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;


#if 0

static_cast 对于隐式类型可以转化的(双重方向上任意一方向可以满足隐式转化),即可用此类型

reinterpret_cast 对于无隐式的类型转化(双重方向都不能转化 static_cast已经不可用)

const_cast 脱const进行操作

dynamic_cast 动态类型转换(涉及多态)
dynamic_cast 一种运行时的类型转化方式, 所以要在运行时作转换判断。检查指针所指
类型,然后判断这一类型是否与正在转换成的类型有一种 “is a”的关系,如果是,
dynamic_cast 返回对象地址。如果不是,dynamic_cast 返回 NULL。
dynamic_cast 常用多态继承中,判断父类指针的真实指向

#endif

#if 0

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

	float a = 5.6;
	int b = 5;
	//a,b俩者可以相互隐式转化 a=b; b=a;
	b = static_cast<int>(a);//将a转为b类型
	a = static_cast<float>(b);//将b转为a类型


	void* p; int* q;
	p = q;//int* 类型可以直接转为void* 类型
	q = static_cast<int*>(p);// p不能直接转为q类型


	int x = 10;
	int y = 3;
	float z = static_cast<float>(x / y);
	cout << z << endl;

	//malloc 在C++中的强转 malloc返回类型为void*
	char* pc = static_cast<char*>(malloc(100));

	return 0;
}
#endif



#if 0
//reinterpret_cast
int _tmain(int argc, _TCHAR* argv[])
{
	//char* p; int* q;
	//p = reinterpret_cast<char*>(q);
	//双方俩个方向上都不能转化的情况下 需要用reinterpret_cast转化

	int a[5] = { 1, 2, 3, 4, 5 };

	int* p = reinterpret_cast<int*>((reinterpret_cast<int>(a)+1)); 
	//先将指针强转为int 加1后再次强转为指针

	cout << hex << *p << endl;

	return 0;
}

#endif


int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值