结构体中的函数指针

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sophisticated_/article/details/82993051

函数指针的定义

一般的函数指针可以这么定义:

int(*func)(int,int);

表示一个指向含有两个int参数并且返回值是int形式的任何一个函数指针. 假如存在这样的一个函数:

    int add(int x,int y)
    {
        return x+y;
    }

那么在实际使用指针func时可以这样实现:

func=&add; //指针赋值,或者func=add; add与&add意义相同

printf(“func(3,4)=%d\n”,func(3,4));

结构体中包含函数指针

其实在结构体中,也可以像一般变量一样,包含函数指针变量.下面是一种简单的实现.

#include <stdio.h>  
struct TEST  
{  
	int x,y;  
	int (*func)(int,int); //函数指针  
};  
  
int add1(int x,int y)  
{  
	return x*y;  
}  
  
int add2(int x,int y)  
{  
	return x+y;  
}  
  
void main()  
{  
	struct TEST test;  
	test.func=add2; //结构体函数指针赋值  
	//test.func=&add2; //结构体函数指针赋值  
	printf("func(3,4)=%d\n",test.func(3,4));  
	test.func=add1;  
	printf("func(3,4)=%d\n",test.func(3,4));  
}  
  
/* 
输出: 
func(3,4)=7 
func(3,4)=12 
*/  

C语言中,如何在结构体中实现函数的功能?把结构体做成和类相似,让他的内部有属性,也有方法
这样的结构体一般称为协议类,提供参考:

#include <stdio.h>  
  
typedef struct  
{  
int a;  
void (*pshow)(int);  
}TMP;  
  
void func(TMP *tmp)  
{  
    if(tmp->a >10)//如果a>10,则执行回调函数。  
    {  
        (tmp->pshow)(tmp->a);  
    }  
}  
  
void show(int a)  
{  
    printf("a的值是%d\n",a);  
}  
  
void main()  
{  
    TMP test;  
    test.a = 11;  
    test.pshow = show;  
    func(&test);  
}  

结构体函数指针赋值

一般使用如下方式给结构体的函数指针赋值,这也是linux内核中使用的方式:

struct test                                        
{
	int (*add) (int a,int b);
	int (*sub) (int a,int b);
	int (*mult) (int a,int b);
};

int  test_add(int a,int b)  
{
   return (a+b);
}
int  test_sub(int a,int b) 
{
   return (a-b);
}
int  test_mult(int a,int b) 
{
   return (a*b);
}

struct test testp={  
	 .add  = test_add, 
	 .sub  = test_sub, 
	 .mult = test_mult,
 };

猜你喜欢

转载自blog.csdn.net/Sophisticated_/article/details/82993051