1. 程式人生 > >c語言中面向介面程式設計

c語言中面向介面程式設計

#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <string>using namespace std;int function1(int a, int b)//c++中,main函式中不能定義函式,只能在全域性中定義,main函式中只能呼叫,c語言中可以{cout << "function1..." << endl;return 0;}int function2(int a, int b){cout << "function2..." << endl;return 0;}//這種形式就是傳遞函式/函式指標,相似於架構函式,類似於多型,形參不變,但根據傳進來的函式不同,執行的結果也不相同//c語言實現類似c++語言的多型是通過函式指標的方式來實現的,在架構函式中,把架構函式的形參寫成函式指標形式void function(int (* p)(int, int), int a, int b){p(a, b);//可變業務}//--------抽象層------------//定義一個錦囊函式,並建立拆開錦囊函式的指標typedef void (TIP)(void);//---------實現層-----------//諸葛亮寫的3個錦囊,一定需要先實現這三個錦囊函式,然後再把錦囊函式的地址賦給錦囊函式指標,或者直接呼叫錦囊函式地址void tip1_func(void){cout << "tip1..." << endl;}void tip2_func(void){cout << "tip2..." << endl;}void tip3_func(void){cout << "tip3..." << endl;}struct superTip{string name;void(*tip)(void);//錦囊函式的指標};//開啟錦囊的架構函式//1.使用抽象層的封裝void open_tips1(TIP *p){p();//函式指標和函式呼叫時不區分,這兒p就是指函數了}//2.不使用抽象層的封裝void open_tips2(void(*p)(void)){p();}void open_superTip(struct superTip tip){tip.tip();//這兒就發生了多型}int main(){//1.定義一個數組型別typedef int(ARRAY_INT_10)[10];int array1[10];//a1 = array1;陣列沒有這種直接賦值的方法,是錯誤的ARRAY_INT_10 a1 = { 1, 2 };//這就定義了一個數組,陣列成員型別為int,成員數量類10a1[0] = 1;    //2.定義一個數組指標typedef int(*ARRAY_INT_20)[20];int array2[20];ARRAY_INT_20 a2 = &array2;(*a2)[0] = 1;//先退化到陣列,在通過陣列正常賦值//3.直接定義陣列指標//ARRAY_INT_20 a2與p意義相同,就是陣列指標int (* p)[20];p = &array2;//1.定義一個函式型別,建議用第三種方式寫函式指標型別,直接用函式型別呼叫函式是沒有任何意義的,一定要用函式指標先賦值函式地址,再通過指標呼叫函式typedef int(FUNC1)(int, int);FUNC1 *f1;f1 = function1;f1(10, 20);//2.定義一個函式指標型別typedef int(*FUNC2)(int, int);FUNC2 f2;f2 = function1;f2(10, 20);//3.直接定義一個指標型別,建議用這種int(*f3)(int, int);f3 = function1;f3(10, 20);function(function1, 1, 1);function(function2, 1, 1);function(f1, 1, 1);TIP *t1 = tip1_func;TIP *t2 = tip2_func;TIP *t3 = tip3_func;//下面九段程式碼都是等價的open_tips1(t1);open_tips1(t2);open_tips1(t3);open_tips1(tip1_func);open_tips1(tip2_func);open_tips1(tip3_func);open_tips2(t1);open_tips2(t2);open_tips2(t3);struct superTip t4;t4.name = "zhugeliang";t4.tip = tip1_func;open_superTip(t4);struct superTip t5;t5.name = "zhaoyun";t5.tip = tip2_func;open_superTip(t5);return 0;}