C++的reinterpret_cast

版权声明:所有的博客都是个人笔记,交流可以留言或者加QQ:2630492017 https://blog.csdn.net/qq_35976351/article/details/85777256

允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。。注意转换的参数是指针,但是不推荐使用。有一种方式比较适合,就是哈希函数的情况:

#include <iostream>

unsigned short Hash(void* p) {
    unsigned int val = reinterpret_cast<unsigned int>(p);
    return static_cast<unsigned int>(val ^ val >> 16);
}

int main() {
    int a[20];
    for (int i = 0; i < 20; ++i){
        a[i] = static_cast<int>(rand() % 10000000);
        std::cout << "num = " << a[i] << ", Hash(" << a[i]
                  << ") = " << Hash(a + i) << "\n";
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/85777256
今日推荐