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

结构体中指向函数的指针(C) && 结构体中的函数(C++)

2014-08-29 15:27 253 查看


结构体中指向函数的指针(C) && 结构体中的函数(C++)  

|举报|字号 订阅

1.结构体中指向函数的指针(C)

C语言中的struct是最接近类的概念,但是在C语言的struct中只有成员,不能有函数,但是可以有指向函数的指针,这也就方便了我们使用函数了。举个例子,如下:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct student

{

 int id;

 char name[50]; 

 void (*initial)();

 void (*process)(int id, char *name);

 void (*destroy)();

}stu;

void initial()

{

 printf("initialization...\n");

}

void process(int id, char *name)

{

 printf("process...\n%d\t%s\n",id, name);

}

void destroy()

{

 printf("destroy...\n");

}

int main()

{

 stu *stu1;

//在VC和TC下都不需要malloc也可以正常运行,但是linux gcc下就会出错,为段错误,必须malloc

 stu1=(stu *)malloc(sizeof(stu));

 // 使用的时候必须要先初始化

 stu1->id=1000;

 strcpy(stu1->name,"xufeng");

 stu1->initial=initial;

 stu1->process=process;

 stu1->destroy=destroy;

 

 printf("%d\t%s\n",stu1->id,stu1->name);

 stu1->initial();

 stu1->process(stu1->id, stu1->name);

 stu1->destroy();

 free(stu1);

 return 0;

}

在linux下编译:gcc -Wall -o test test.c

输出结果:

1000    xufeng

initialization...

process...

1000    xufeng

destroy...

c语言中,如何在结构体中实现函数的功能?把结构体做成和类相似,让他的内部有属性,也有方法

这样的结构体一般称为协议类,提供参考: 

struct { 

 int funcid; 

 char *funcname; 

 int (*funcint)(); /* 函数指针 int 类型*/ 

 void (*funcvoid)(); /* 函数指针 void类型*/ 

}; 

每次都需要初始化,比较麻烦

2.结构体中的函数(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();

}

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

在linux下编译:g++ -Wall -o test1 test1.c

输出结果:

after init,m=33

function of struct.

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

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

再来一例:

//g++ -Wall -o struct_test struct_test.c

#include <stdio.h>

struct test

{

 int i;

 void set(int m_i)

 {

  i=m_i;

 }

 void get()

 {

  printf("%d\n",i);

 }

 void (* find)();

};

void find ()

{

 printf("hello find\n");

};

int main()

{

 test a;

 a.find =&find;

 a.set(1000);

 a.get();

 a.find();

 return 0;

}

输出结果:

1000

hello find

欢迎大家交流!

本文为网络资料收集整理,转载请注明出处:http://hujw0710.blog.163.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: