2012-09-28 38 views
21

我想将一些C++代码转换为C,并且遇到问题。 是否可以在结构中定义一个函数?可能在C结构中定义一个函数吗?

像这样:

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

回答

32

不,你不能一个struct内C.

定义一个函数

您可以在一个struct函数指针虽然,但有一个函数指针是非常不同的C++中的成员函数,即不存在隐含的指向包含struct实例的指针this

人为的例子(在线演示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; 
} 
7

C不允许以限定内部struct的方法。你可以定义一个函数指针的结构体内部如下:

typedef struct { 
    double x, y, z; 
    struct Point *next; 
    struct Point *prev; 
    void (*act)(); 
} Point; 

以后每次你实例struct指针分配给特定的功能。

2

这个想法是把一个指针指向一个函数结构。然后该函数被声明在结构之外。这与C++中的类中声明函数的类不同。

例如:从这里窃取代码:http://forums.devshed.com/c-programming-42/declaring-function-in-structure-in-c-545529.html

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++不同的位置定义函数指针。

11

虽然你可以在结构中有一个函数指针。

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; 

} 
:但不能以这种方式

你可以用这种方式

例如把它定义

相关问题