C語言中的結構體內嵌函式
阿新 • • 發佈:2018-12-10
1.內嵌函式定義舉例:經過真實測試
在函式中宣告定義結構體
- #include "fun_in_struct.h"
- int main(int argc, char **argv) {
- //定義結構體指標或者結構體變數,分別用->和.進行內部元素的使用
- data_store_object *obj;
- char *word;
- /*方法一:直接定義結構體指標然後用->對結構體變數和函式進行初始化
- word = "nihao";
- obj = calloc(1,sizeof(data_store_object));
- obj->word = word;
- obj->count = 24;
- obj->word_print = WordPrint;
- obj->count_print = CountPrint;
- obj->word_print(obj->word);
- printf("%d\n",obj->count_print(obj->count));
- return 0;
- */
- /*方法二:直接定義結構體變數然後直接進行初始化,用 變數 = xxx;進行賦值
- data_store_object obj = {
- .word = "nihao",
- .count = 12,
- .word_print = WordPrint,
- .count_print = CountPrint
- };
- obj.word_print(obj.word);
- printf("%d\n",obj.count_print(obj.count));
- return 0;
- */
- /*方法三:直接定義結構體變數,然後使用 變數 : xx進行賦值
- data_store_object obj = {
- word : "nihao",
- count : 33,
- word_print : WordPrint,
- count_print : CountPrint
- };
- obj.word_print(obj.word);
- printf("%d\n",obj.count_print(obj.count));
- return 0;
- */
在標頭檔案中對結構體進行定義:
- typedef struct {
- char *word;
- int count;
- void (*word_print)(char *word);
- int (*count_print)(int count);
- }data_store_object;
- 進行兩個函式的宣告,函式的定義發生在其他的原始檔
- void WordPrint(char *word);
- int CountPrint(int count);
2.內嵌函式的個人理解
- C語言的結構體內部是可以定義函式的,就像java中定義方法一樣,我們在構建物件的時候不止是可以使用它的引數,還可以使用它內部關於資料的處理函式,java中叫做方法;但是C語言並不能實現類中方法的繼承,過載,重寫等特性,因此用的不是很多;
- C語言是可以面向物件的,面向物件是一種思想,將事物和做事的過程定義成物件,只是C語言的語法讓面向物件變得不那麼好用。
- C語言是要轉化為組合語言再轉化為機器語言執行的,在組合語言中存在著宣告程式碼段的過程,將一段彙編指令之前加上一個標號,而這個標號就是函式的名稱,我們所說的函式名實際上代表了一段構彙編指令的初始記憶體地址。那麼變數可以附地址,函式也是可以的,有興趣的可以看一下組合語言和C語言混合程式設計,就理解了內嵌函式中出現的函式指標。
博文借鑑了其他人的部落格,無意抄襲,侵刪;順便吐槽一下這個爛編輯器,真難用。