电视剧我的特一营插曲:结构体与函数指针的特殊应用-如何在c语言中实现多态
来源:百度文库 编辑:中财网 时间:2024/04/30 04:05:26
//-----------------------------------------------------------//
#include
struct A
{
};
void myfun1()
{
}
int myfun2(int a)
{
}
char myfun3(int a)
{
}
int main()
{
}
//-----------------------------------------------------------//
在GCC4.0下编译运行的结果如下:
//-----------------------------------------------------------//
hill@hill-laptop:~/Desk/temp$ gcc test4.c
test4.c: 在函数 ‘main’ 中:
test4.c:25: 警告:从不兼容的指针类型赋值
test4.c:30: 警告:从不兼容的指针类型赋值
hill@hill-laptop:~/Desk/temp$ ./a.out
this is fun(-1208768727)
AAA
this is fun(4)
AAA1
this is fun(43)
AAA2
this is fun(
AAA
this is fun()
AAA1
this is fun(+)
AAA2
hill@hill-laptop:~/Desk/temp$
//-----------------------------------------------------------//
现在分析一下上面的代码:
首先,这个程序的思路是想用一个结构体模拟一个类,通过函数指针来申明“类”方法,并模拟多态性。
是一个函数指针,注意,这里不要写成
接下来写了两个函数
在接下来的main函数中,我们为A实例a的fun域赋值,这里我们直接赋值了myfun2,若上面方法申明中采用(2),那么将不能把myfun2赋值给fun,因为void*是可以指向任何类型的指针,那么当然可以指向int。这里又定义了myfun3就是为类看看void*是否能自动的转化为char类型了。
这是因为C毕竟还是一个静态语言的原因。
struct file_operations {
int (*seek) (struct inode * ,struct file *, off_t ,int);
int (*read) (struct inode * ,struct file *, char ,int);
int (*write) (struct inode * ,struct file *, off_t ,int);
int (*readdir) (struct inode * ,struct file *, struct dirent * ,int);
int (*select) (struct inode * ,struct file *, int ,select_table *);
int (*ioctl) (struct inode * ,struct file *, unsined int ,unsigned long
int (*mmap) (struct inode * ,struct file *, struct vm_area_struct *);
int (*open) (struct inode * ,struct file *);
int (*release) (struct inode * ,struct file *);
int (*fsync) (struct inode * ,struct file *);
int (*fasync) (struct inode * ,struct file *,int);
int (*check_media_change) (struct inode * ,struct file *);
int (*revalidate) (dev_t dev);
}
具体设备驱动程序的编写已经超出本文范围,日后再说明。
小结:
c语言中,如何在结构体中实现函数的功能?
在C语言中,指针与数组的区别
(C语言)返回指向数组的指针的函数
C语言文件位置指针的操作函数问题
C语言关于结构体指针的地址传递问题!!在线等
关于指针与结构的一段C程序。
请问C语言有什么网络应用的函数?
数组、函数、指针的综合应用
C语言指针的问题!~
c语言的指针变量
c 语言的指针题
c 语言的指针题
c 语言的指针题
C语言的指针问题
c语言结构体
C语言中的数组与指针问题
C语言指针与数组问题,不明白。
用C语言编写意义的程序(只能用函数和指针编写)
在c 语言中的”指针“的具体定义是?
什么叫远指针?在什么情况下需要使用远指针?远指针要如何使用?(C语言)
C语言中调用函数的返回值只要是指针,定义函数是不是就得加*
C语言如何调用函数
如何查C语言函数
为什么c语言中在函数中定义指针变量总有警告说在定义以前使用了它?