【C++】 标准运算符

/*
static_cast和reinterpret_cast一样,在面对const的时候都无能为力:
两者都不能去除const限定。两者也存在的很多的不同,
比如static_cast不仅可以用在指针和引用上,还可以用在基础数据和对象上;
前面提到过reinterpret_cast可以用在"没有关系"的类型之间,
而用static_cast来处理的转换就需要两者具有"一定的关系"了。
*/
// 实例验证
#include <iostream>
using namespace std;
unsigned short Hash( void *p )
{
	unsigned long val = reinterpret_cast <unsigned long>( p );
	return ( unsigned short ) ( val ^ (val >> 16) );
}

class Something
{
	/* Come Codes here */
};

class Otherthing
{
	/* Come Codes here */
};

int main()
{
	typedef unsigned short (*FuncPointer) ( void* );
	FuncPointer fp = Hash; // right,this is what we want

	int a[10];
	const int* ch = a; // right, array is just like pointer
	char chArray[4] = {'a','b','c','d'};

	fp = reinterpret_cast<FuncPointer> (ch); // no arror,but does't make sense
	ch = reinterpret_cast<int*> (chArray);	// no error

	cout << hex << *ch; // output:64636261	// it really reinerpret the pointer
	
	Something *st = new Something();
	Otherthing *ot = reinterpret_cast<Otherthing*> (st);
// cast between objects with on relationship

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u013346007/article/details/78076508