您的位置:首页 > 编程语言 > C语言/C++

在C/C++中的struct使用函数指针,而且在C++中的struct还能使用成员函数

2017-07-03 10:27 405 查看
[转载] http://blog.csdn.net/xcxinghai/article/details/6729539

[转载] http://blog.csdn.net/bit_x/article/details/5658137

1、函数指针

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

int(*func)(int,int);


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

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


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

func=&add2; //指针赋值,或者func=add2; add2与&add2意义相同
printf("func(3,4)=%d\n",func(3,4));


事实上,为了代码的移植考虑,一般使用typedef定义函数指针类型.

typedef int(*FUN)(int,int);
FUN func=&add2;
func();


2、结构体中包含函数指针

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

#include "stdio.h"
struct DEMO
{
int x,y;
int (*func)(int,int); //函数指针
};
int add2(int x,int y)
{
return x+y;
}
void main()
{
struct DEMO demo;
demo.func=&add2; //结构体函数指针赋值
printf("func(3,4)=%d\n",demo.func(3,4));
}


上面的文件保存为mytest.c,在VC6.0和gcc4中编译通过.

3、C++允许结构体中有成员函数

既然在C++中介绍类的时候说过“类是取代结构体的”。可见结构体的功能并非我们平时用到的这么简单,没有太多人知道结构体中也可以有自己的函数成员。

也就是说,在C++中允许结构体包含函数成员,而标准C不支持。 进一步发现,c++中甚至允许结构体中含有构造函数、重载、public/private等等.这样看来,结构体真的与类越来越靠近相似了!

C++扩充了结构体的功能。但C++中为了介绍面向对象的类,却淡化了同样精彩的结构体。当我们写一些小程序而觉得没有必要去构造类的时候,选择结构体确实会方便很多。

举个例子:

#include "stdio.h"
struct DEMO
{
int m;
DEMO(int k) //构造函数
{
this->m=k;
printf("after init,m=%d\n",m);
}
void func()//一般函数
{
printf("function of struct.\n");
}
};

void main()
{
struct DEMO demo(33);
demo.func();
}


保存为mytest1.c , VC6.0和gcc编译都会出错。这可能说明标准C是不支持结构体包括函数成员形式的(因为后缀.c使得VC或gcc选择c编译器)。 但是如果将文件后缀改为.cpp(也就是选择c++编译),就不再有错误了,得到结果:

after init,m=33
function of struct.


4. C语言实现类中方法——用函数指针在结构体中加入函数

first.h如下所示

/********* first.h *********/
#ifndef __FIRST__H_H
#define __FIRST__H_H

//way1:
struct test_st
{
int elem;
char* (*get_char)(char *str);
int (*get_int)(int in);
};

//way2: 先使用typedef声明函数指针类型,再在struct中使用该函数指针类型的变量
typedef char* (*type_get_char)(char *str);
typedef int (*type_get_int)(int in);
typedef struct test_st
{
int elem;
type_get_char get_char;
type_get_int get_int;
}a_test_st;

#endif


first.c 如下所示

/********* first.c *********/
#include <stdio.h>
#include <string.h>
#include "first.h"

char *my_get_char(char *str);
int my_get_int(int in);

int main( void )
{
a_test_st *aTestSt;
char aStr[] = "abcdefg";
char *pStr = NULL;
int aInt = 0;
//申请内存空间
aTestSt = (a_test_st*)malloc(sizeof( a_test_st));
//为结构中变量赋值
memset(aTestSt, 0, sizeof(a_test_st));
aTestSt->elem = 45;
aTestSt->get_char = my_get_char;//为aTestSt中函数指针赋值
aTestSt->get_int = my_get_int;//为aTestSt中函数指针赋值

pStr = aTestSt->get_char( aStr);//调用aTestSt的函数
printf("aStr = %s/n",aStr);
aInt = aTestSt->get_int( aTestSt->elem);//调用aTestSt的函数
printf("aInt = %d/n", aInt);

free(aTestSt);//释放aTestSt所指向内存空间
aTestSt = NULL;//置空
return 0;
}

char *my_get_char(char *str)
{//将str前两个字符返回
char *pstr = NULL;
pstr = str;
*pstr = *str;
*(pstr + 1) = *(str + 1);
*(pstr + 2) = '/0';

return pstr;
}

int my_get_int(int in)
{
return in + 2;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct c语言 指针