函式指標 typedef 用法 回撥函式 結構體儲存函式地址
阿新 • • 發佈:2019-01-06
#include <stdio.h> #include<stdlib.h> //01定義簡單函式 void f1(int a) { printf("hello\n"); } void f2(int a) { printf("world\n"); } //02 typedef 用法 typedef int myint; //給已有的型別 起 別名 方便使用 typedef void(*type)(int); //03--函式指標作為形參--------回撥函式 void func(type p, int a) { p(a); } //04 結構體儲存函式地址,實現面向物件的思想 struct stu { int age; int(*speak)(int); }; int shuo(int a) { printf("hello world"); return 0; } void test1() { //函式指標變數定義 void(*p)(int) = NULL; p = f1; p(1); p = f2; p(2); } void test2() { //函式指標變數定義 type p = NULL; p = f1; p(1); p = f2; p(2); } void test3() { int a = 0; func(f1, a); func(f2, a);//回撥函式 } void test4() { struct stu s; s.age = 100; s.speak = shuo; printf("age:%d----speak:%d", s.age, s.speak(1)); } void main() { //test1(); //test2(); //test3(); test4(); getchar(); }