2012-09-28 37 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; 

} 
:但不能以這種方式

你可以用這種方式

例如把它定義

相關問題