请问,如何用标准C如何实现多态?
如题,最好有相关的说明,多谢!
c++的特点就是 多态 派生 继承这些!
c语言实现不的!都不能重载的!
[解决办法]
参考我的系列博文http://blog.csdn.net/turingo/article/details/8516327。
//codegen.c
// 输入一组字符串,比如
// aa ss ddd dd 33 dd
// 然后自动生成一个函数 int A(const char*);
// 实现A("aa")返回0 A("ss")返回1 依次类推
#include <stdio.h>
int main(int argc,char **argv) {
int i;
if (argc<2) {
printf("%s p1 [p2 ...] [>result.c]\nGenerate code int A(const char *a); 0==A("p1") 1==A("p2") ...",argv[0]);
return 1;
}
//printf("#include <string.h>\n");
printf("int A(const char *a) {\n");
for (i=0;i<argc-1;i++) {
printf(" if (0==strcmp(a,"%s")) return %d;\n",argv[i+1],i);
}
printf(" return -1;\n");
printf("}\n");
return 0;
}
//C:\test\Debug>codegen.exe
//codegen.exe p1 [p2 ...] [>result.c]
//Generate code int A(const char *a); 0==A("p1") 1==A("p2") ...
//C:\test\Debug>codegen.exe aa ss ddd dd 33 dd
//int A(const char *a) {
// if (0==strcmp(a,"aa")) return 0;
// if (0==strcmp(a,"ss")) return 1;
// if (0==strcmp(a,"ddd")) return 2;
// if (0==strcmp(a,"dd")) return 3;
// if (0==strcmp(a,"33")) return 4;
// if (0==strcmp(a,"dd")) return 5;
// return -1;
//}
//
//c:\test\Debug>codegen.exe aa ss ddd dd 33 dd >result.c
//
//c:\test\Debug>type result.c
//int A(const char *a) {
// if (0==strcmp(a,"aa")) return 0;
// if (0==strcmp(a,"ss")) return 1;
// if (0==strcmp(a,"ddd")) return 2;
// if (0==strcmp(a,"dd")) return 3;
// if (0==strcmp(a,"33")) return 4;
// if (0==strcmp(a,"dd")) return 5;
// return -1;
//}
//
struct naiveSimulatation
{
typedef void (*Foo)(int);
typedef void (*Foo2)(float, float);
Foo foo;
Foo2 foo2;
//......
};
void print_int(int value)
{
//std::cout<<value<<std::endl;
printf("%d\n", value);
}
void print_float(float a, float b)
{
//std::cout<<a<<", "<<b<<std::endl;
printf("%f, %f\n", a, b);
}
int main()
{
naiveSimulatation sss;
sss.foo = print_int;
sss.foo2 = print_float;
sss.foo(444);
return 0;
}
AdtatImpl a;
};
};
void func(struct dataheader *head);
void func_AData(struct dataheader *head);
struct dataheader *head=malloc (sizeof(AData));
typedef void (*Func_Calc)(struct dataheader *head);
Func_Calc f[10];
void InstallFunc(struct dataheader *head,Func_Calc &f)
{
if(head->size ==sizeof(dataheader))
f = func;
else f = func_AData;
}
int main()
{
struct dataheader d;
struct Adata a ;
struct dataheader *p[10]={&d,&a};
for(i=0;i<2;i++)
InstallFunc(p+i,f+i);
for(i=0;i<2;i++)
f[i](p+i);
return 0;
}
大概类似种种方法,具体看下驱动程序的开发方式,和 libtiff源码
这些都是C实现,类似C++多态的方式 。