Can I define a function inside a C structure?

67

我正在尝试将一些C++代码转换为C,并且遇到了一些问题。如何在结构体内定义一个函数?

就像这样:

 typedef struct  {
    double x, y, z;
    struct Point *next;
    struct Point *prev;
    void act() {sth. to do here};
} Point;
6个回答

95

不,你无法在C语言的struct中定义一个函数。

你可以在struct中使用函数指针,但是在C++中拥有函数指针与成员函数是非常不同的,因为在C语言中没有隐式的this指针指向包含struct实例。

下面是一个人为的示例(在线演示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;
}

1
point* 的意思是什么?我的意思是,在变量名后面加*有什么含义? - explorer
'point' 是结构体的类型名称。'p' 是变量。 - Rathnavel
1
更准确地说,point* p 表示将指向结构体的指针作为参数传递。这样可以节省内存(按值传递会在堆栈上创建变量的副本)。point* 表示它是指向结构体 p 的指针,而不仅仅是 point,后者表示它是一个结构体,并将作为原始结构体的副本进行传递。 - Parth Sarthi Sharma

21

虽然不能用这种方式,但是你可以在结构体中定义一个函数指针。

你可以按照下面的方式定义:

例如:

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;
}

9
在C语言中,不允许在结构体内定义方法。但是你可以在结构体中定义一个函数指针,如下所示:
typedef struct  {
  double x, y, z;
  struct Point *next;
  struct Point *prev;
  void (*act)();
} Point;

每当你实例化 struct 时,你需要将指针分配给特定的函数。


8

3

这个想法是在结构体中放置一个指向函数的指针,然后将函数声明在结构体外部。这与C++中在类内部声明函数不同。

例如:从这里窃取代码:

struct t {
    int a;
    void (*fun) (int * a);
} ;

void get_a (int * a) {
    printf (" input : ");
    scanf ("%d", a);
}

int main () {
    struct t test;
    test.a = 0;

    printf ("a (before): %d\n", test.a);
    test.fun = get_a;
    test.fun(&test.a);
    printf ("a (after ): %d\n", test.a);

    return 0;
}

在这里,test.fun = get_a; 将函数分配给结构体中的指针,test.fun(&test.a); 调用它。


1
在C编程语言中,您只能在结构体中定义函数指针,这与C++不同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接