要测试intptr
转换的正确性,您需要编写一些测试用例来验证不同类型的数据在转换为intptr_t
后是否能够正确地还原
#include<iostream>
#include <cstdint>
intptr_t
转换回原始类型:template<typename T>
T intptr_to_type(intptr_t ptr) {
return reinterpret_cast<T>(ptr);
}
int main() {
// 测试用例1:int
int a = 42;
intptr_t int_ptr = reinterpret_cast<intptr_t>(&a);
int* restored_int_ptr = intptr_to_type<int*>(int_ptr);
std::cout << "Test case 1 (int): " << ((*restored_int_ptr == a) ? "Passed" : "Failed")<< std::endl;
// 测试用例2:float
float b = 3.14f;
intptr_t float_ptr = reinterpret_cast<intptr_t>(&b);
float* restored_float_ptr = intptr_to_type<float*>(float_ptr);
std::cout << "Test case 2 (float): " << ((*restored_float_ptr == b) ? "Passed" : "Failed")<< std::endl;
// 测试用例3:自定义结构体
struct TestStruct {
int x;
float y;
};
TestStruct c{10, 20.5f};
intptr_t struct_ptr = reinterpret_cast<intptr_t>(&c);
TestStruct* restored_struct_ptr = intptr_to_type<TestStruct*>(struct_ptr);
std::cout << "Test case 3 (struct): " << ((restored_struct_ptr->x == c.x && restored_struct_ptr->y == c.y) ? "Passed" : "Failed")<< std::endl;
return 0;
}
这些测试用例分别测试了int
、float
和自定义结构体类型的数据。通过比较转换前后的值,可以验证intptr
转换的正确性。如果所有测试用例都通过,那么intptr
转换应该是正确的。