要測試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
轉換應該是正確的。