C中struct的函数指针

时间:2015-04-07 18:31:02

标签: c

我正在尝试理解C语法,并且我已经完成了以下示例。我已经将函数指针*func放置为我的Person结构的属性,该结构返回struct Person

typedef struct
{
    int age, salary;
    struct Person(*func) (int age, int salary);
} Person;

Person other_func(int age, int salary)
{
    Person* person = malloc(sizeof(Person));
    person->age = age;
    person->salary = salary;
    return *person;
};

int main()
{
    Person p;
    p.func= other_func;
    p = p.func(30, 3000);
}

这给了我"无法将人转换为人"在最后一行。我想这是因为一个是Person而第二个是struct Person,但是在Person结构中,我的函数为struct Person(*func_1) (int age, int salary);,因为它提高了编译时间如果我使用Person而不是struct Person,则会出错。所以我使用了struct Person代替。这是问题吗?我如何实现我想做的事情?

2 个答案:

答案 0 :(得分:4)

typedef struct
{
    int age, salary;
    struct Person(*func) (int age, int salary);
} Person;

不应该是:

typedef struct Person
{
    int age, salary;
    struct Person(*func) (int age, int salary);
} Person;

在第一种情况下,您没有为结构命名,因此struct Person不是有效的类型名称。我的GCC版本提供了更多有用的输出:

$ gcc test.c
test.c: In function ‘main’:
test.c:20:11: warning: assignment from incompatible pointer type
     p.func= other_func;
           ^
test.c:21:5: error: invalid use of undefined type ‘struct Person’
     p = p.func(30, 3000);

请注意,这两个名称不需要匹配。您所做的只是组合一个typedef和一个struct声明。这同样有效:

struct X {
    int age, salary;
    struct X(*func) (int age, int salary);
};

typedef struct X Person;

您可能需要阅读this excellent answer about struct typedef'ing

答案 1 :(得分:2)

typedef struct X {} Y;

X - 是一个TAG,您可以使用语法' struct X val '将其转换为有用的东西。 Y 是你可以直接使用的typename:'Y val;'

然后,键入名称Y(在您的情况下,'Person'在struct中不可见,因为它稍后定义。这就是为什么你必须在struct中使用TAG:

typedef struct tag_Person {
    struct tag_Person (*func)(int arge, int salary);
} Person;