我可以在C结构中定义一个函数吗?

DCu*_*ser 45 c structure function

我试图将一些C++代码转换为C,我遇到了一些问题.如何在结构内部定义函数?

像这样:

 typedef struct  {
    double x, y, z;
    struct Point *next;
    struct Point *prev;
    void act() {sth. to do here};
} Point;
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 60

不,你不能struct在C中定义一个函数.

你可以在一个函数指针中使用函数指针,struct但函数指针与C++中的成员函数非常不同,即没有this指向包含struct实例的隐式指针.

Contrived example(在线演示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;
}
Run Code Online (Sandbox Code Playgroud)


MOH*_*MED 14

您可以在结构中使用函数指针.但不是这样

你可以用这种方式定义它

例:

typedef struct cont_func 
{
    int var1;
    int (*func)(int x, int y);
    void *input;
} cont_func;


int max (int x, int y)
{
    return (x > y) ? x : y;
}

int main () {
   struct cont_func T;

   T.func = max;
}
Run Code Online (Sandbox Code Playgroud)


Sal*_*gar 7

不,不可能在C中的结构内声明一个函数.

这是(C之一)C和C++之间的根本区别.

请参阅此主题:http://forums.devshed.com/c-programming-42/declaring-function-in-structure-in-c-545529.html


eps*_*lon 7

C其中不允许在a中定义方法struct.您可以在结构中定义函数指针,如下所示:

typedef struct  {
  double x, y, z;
  struct Point *next;
  struct Point *prev;
  void (*act)();
} Point;
Run Code Online (Sandbox Code Playgroud)

每当实例化时,都必须将指针指定给特定的函数struct.