Gri*_*han 7 c oop struct coding-style structure
我不是C编程的新手.但是我不明白将指针作为C中的结构成员保持指示是有用的.例如
// Fist Way: To keep pointer to function in struct
struct newtype{
int a;
char c;
int (*f)(struct newtype*);
} var;
int fun(struct newtype* v){
return v->a;
}
// Second way: Simple
struct newtype2{
int a;
char c;
} var2;
int fun2(struct newtype2* v){
return v->a;
}
int main(){
// Fist: Require two steps
var.f=fun;
var.f(&var);
//Second : simple to call
fun2(&var2);
}
Run Code Online (Sandbox Code Playgroud)
程序员是否使用它来为C代码提供面向对象(OO)形状并提供抽象对象?或者使代码看起来技术性.
我认为,在上面的代码中,第二种方式也更温和,也很简单.在第一种方式,我们仍然必须通过&var,甚至fun()是结构的成员.
如果将结构定义中的函数指针保持良好,请帮助解释其原因.
tom*_*ahh 11
提供指向结构上的函数的指针可以使您能够动态选择要对结构执行的函数.
struct newtype{
int a;
int b;
char c;
int (*f)(struct newtype*);
} var;
int fun1(struct newtype* v){
return v->a;
}
int fun2(struct newtype* v){
return v->b;
}
void usevar(struct newtype* v) {
// at this step, you have no idea of which function will be called
var.f(&var);
}
int main(){
if (/* some test to define what function you want)*/)
var.f=fun1;
else
var.f=fun2;
usevar(var);
}
Run Code Online (Sandbox Code Playgroud)
这使您能够拥有一个调用接口,但根据您的测试是否有效调用两个不同的函数.
Ani*_*nge 10
如果您尝试进行某种"基于对象"的编程,它很有用.
如果您曾经见过Quake 3引擎的源代码,您可以清楚地看到大多数"实体"具有定义它们的属性,以及它们所做的工作[它们是函数指针].
隔离属性和函数(通过C中的函数指针)定义了"struct"对象的属性和它们可以执行的操作.
例如:
struct _man{
char name[];
int age;
void (*speak)(char *text);
void (*eat)(Food *foodptr);
void (*sleep)(int hours);
/*etc*/
};
void grijesh_speak(char *text)
{
//speak;
}
void grijesh_eat(Food *food)
{
//eat
}
void grijesh_sleep(int hours)
{
//sleep
}
void init_struct(struct _man *man)
{
if(man == NULL){ man = malloc(sizeof(struct _man));}
strcpy(*man.name,"Grijesh");
man->age = 25;
man->speak = grijesh_speak;
man->eat = grijesh_food;
man->sleep = grijesh_sleep;
//etc
}
//so now in main.. i can tell you to either speak, or eat or sleep.
int main(int argc, char *argv[])
{
struct _man grijesh;
init_struct(&grijesh);
grijesh.speak("Babble Dabble");
grijesh.sleep(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)