[問題] 有關struct

看板C_and_CPP作者 (andy821201)時間8年前 (2016/03/25 21:06), 編輯推噓3(309)
留言12則, 7人參與, 最新討論串1/1
剛剛讀到有關struct的問題 #include <stdio.h> #include <stdlib.h> void main(){ struct test{ int math; int english; }; typedef struct test score; score joe, jane; /* test joe, jane;*/ joe.math = 80; joe.english = 75; jane.math = 95; jane.english = 68; printf("%d\n", joe.math); printf("%d\n", joe.english); printf("%d\n", jane.math); printf("%d\n", jane.english); system("pause"); } 想請問各位前輩 typedef struct test score score joe,jane; 這段的用意是甚麼呢? 我用 test joe,jane; 也是可以達到一樣的執行結果 我看書上宣告test joe,jane 前面都會加上struct的關鍵字 所以說用typedef 重新定義後就可以不用每次都要加struct 不過我測試後不加struct 程式的執行結果是一樣的 所以想知道這兩種寫法是否會有差異 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.42.43.137 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1458911217.A.C19.html

03/25 21:13, , 1F
C 需要用 struct test , C++ 不用
03/25 21:13, 1F

03/25 21:41, , 2F
C++ 以後就基本沒差別了
03/25 21:41, 2F

03/26 23:41, , 3F
typedef struct test score 意思是幫 test 結構取個別名叫作
03/26 23:41, 3F

03/26 23:42, , 4F
score 而已, 就像有人會用 typedef int salary 這樣把 int
03/26 23:42, 4F

03/26 23:42, , 5F
取個別名叫 salary , 然後就用 salary jack ; 去宣告 jack
03/26 23:42, 5F

03/26 23:43, , 6F
的薪水
03/26 23:43, 6F

03/26 23:44, , 7F
和你直接用 int jack ; 來代表 jack 的薪水一樣, 易讀而已
03/26 23:44, 7F

03/27 15:29, , 8F
可是我很討厭同一個東西有好幾個名字XDDD
03/27 15:29, 8F

03/28 02:15, , 9F
有時候取別名是因為把舊有struct或 data type 挪作他用
03/28 02:15, 9F

03/28 02:15, , 10F
為了讓它在新用途上名符其實才需要另取個新名字
03/28 02:15, 10F

03/28 15:42, , 11F
看了P大的回覆 讓我懂了用這個的用意 感謝p大
03/28 15:42, 11F

03/28 16:28, , 12F
說穿了就是抽象化
03/28 16:28, 12F
文章代碼(AID): #1MzJVnmP (C_and_CPP)