C struct 隐藏结构体成员
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\n", 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\n", GetId(o1), GetName(o1)); 73 74 puts("\n按回车键继续"); 75 getchar(); 76 return 0; 77 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步