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,成员数量类10
a1[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;
}


猜你喜欢

转载自blog.csdn.net/tulipless/article/details/80939804