可能在C结构中定义一个函数? [英] possible to define a function inside a C structure?
本文介绍了可能在C结构中定义一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将一些C ++代码转换为C,并且遇到问题。
是否可以在结构中定义一个函数?
像这样:
typedef struct {
double x,y,z;
struct Point * next;
struct Point * prev;
void act(){sth。在这里做};
}点;
解决方案
不能,您不能在<$你可以在 struct $ c $>中有一个函数指针,这个函数指针指向C中的c $ c> struct
。但是有一个函数指针与C ++中的成员函数有很大的不同,即没有隐含的 this
指向包含 struct
instance。
构建示例(在线演示 http:
#include
#include< string.h>
#include< stdlib.h>
struct point
{
int x;
int y;
void(* print)(const struct point *);
};
void print_x(const struct point * p)
{
printf(x =%d \ n,p-> x);
}
void print_y(const struct point * p)
{
printf(y =%d \ n,p-> y);
}
int main(void)
{
struct point p1 = {2,4,print_x};
struct point p2 = {7,1,print_y};
p1.print(& p1);
p2.print(& p2);
返回0;
}
I am trying to convert some C++ code to C and I am having problems. Is it possible to define inside a structure a function?
Like this:
typedef struct {
double x, y, z;
struct Point *next;
struct Point *prev;
void act() {sth. to do here};
} Point;
解决方案
No, you cannot define a function within a struct
in C.
You can have a function pointer in a struct
though but having a function pointer is very different from a member function in C++, namely there is no implicit this
pointer to the containing struct
instance.
Contrived example (online demo http://ideone.com/kyHlQ):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct point
{
int x;
int y;
void (*print)(const struct point*);
};
void print_x(const struct point* p)
{
printf("x=%d\n", p->x);
}
void print_y(const struct point* p)
{
printf("y=%d\n", p->y);
}
int main(void)
{
struct point p1 = { 2, 4, print_x };
struct point p2 = { 7, 1, print_y };
p1.print(&p1);
p2.print(&p2);
return 0;
}
这篇关于可能在C结构中定义一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文