【C++】 标准运算符

来源:互联网 发布:js 修改style属性 编辑:程序博客网 时间:2024/06/03 15:19
/*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 wantint a[10];const int* ch = a; // right, array is just like pointerchar chArray[4] = {'a','b','c','d'};fp = reinterpret_cast<FuncPointer> (ch); // no arror,but does't make sensech = reinterpret_cast<int*> (chArray);// no errorcout << hex << *ch; // output:64636261// it really reinerpret the pointerSomething *st = new Something();Otherthing *ot = reinterpret_cast<Otherthing*> (st);// cast between objects with on relationshipsystem("pause");return 0;}

原创粉丝点击