标签:cin using har read lib bsp char style div
1 #include <iostream> 2 #include <string> 3 #include <stdio.h> 4 #include <stdlib.h> 5 using namespace std; 6 7 struct Person 8 { 9 int age; 10 int id; 11 }; 12 13 template <class T> T myRead(void * memory) 14 { 15 char buffer[sizeof(T)]; 16 memcpy(buffer, memory, sizeof(T)); 17 T temp = *((T *)buffer); // 调用 Person 拷贝构造 18 return temp; 19 } 20 21 template <class T> T myRead2(void * memory) 22 { 23 T temp; 24 memcpy(&temp, memory, sizeof(T)); 25 return temp; 26 } 27 28 29 30 int main() 31 { 32 char bytes[20] = "\x05\x00\x00\x00\x0A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; 33 Person p = myRead<Person>(bytes); // 调用 Person 拷贝构造 34 printf("age = %d, id = %d\n", p.age, p.id); 35 36 Person p2 = myRead2<Person>(bytes); // 调用 Person 拷贝构造 37 printf("age = %d, id = %d\n", p2.age, p2.id); 38 39 40 cin.get(); 41 return 0; 42 }
执行结果
1 age = 5, id = 10 2 age = 5, id = 10
标签:cin using har read lib bsp char style div
原文地址:https://www.cnblogs.com/redc/p/Temp_2018_12_26_02.html