1 //obj.h 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 typedef struct Obj Obj; 8 9 Obj * CreateObject(int id, const char * name); 10 11 void PrintObject(Obj * obj); 12 13 int GetId(Obj * obj); 14 15 char * GetName(Obj * obj); 16 17 18 //obj.c 19 20 #include "obj.h" 21 22 struct Obj { 23 int id; 24 char name[32]; 25 }; 26 27 Obj * CreateObject(int id, const char * name) 28 { 29 Obj * ret = (Obj*)malloc(sizeof(Obj)); 30 if (ret) 31 { 32 ret->id = id; 33 strcpy_s(ret->name, 32, name); 34 } 35 return ret; 36 } 37 38 void PrintObject(Obj * obj) 39 { 40 printf("obj->id = %d, obj->name = %s ", obj->id, obj->name); 41 } 42 43 int GetId(Obj * obj) 44 { 45 return obj->id; 46 } 47 48 char * GetName(Obj * obj) 49 { 50 return obj->name; 51 } 52 53 //main.c 54 55 #include <stdio.h> 56 #include <stdlib.h> 57 #include <string.h> 58 #include "obj.h" 59 60 int main() 61 { 62 Obj * o1 = NULL; 63 Obj * o2 = NULL; 64 65 char name[32] = "two"; 66 o1 = CreateObject(10, "ten"); 67 o2 = CreateObject(2, name); 68 69 PrintObject(o1); 70 PrintObject(o2); 71 72 printf("o1->id = %d, o1->name = %s ", GetId(o1), GetName(o1)); 73 74 puts(" 按回车键继续"); 75 getchar(); 76 return 0; 77 }