0

如果我有一个结构,它有一个指向这样的函数的指针

struct str{
 int some_element;
 char other_element;
 int (*my_pointer_to_a_function)(int);
};

struct str my_struct;
int my_function(int);

我给它赋值

my_struct.some_element = 1;
my_struct.other_element = 'a';
my_struct.my_pointer_to_a_function = my_function;

如何调用指针指向的函数(使用指针)?我最初的猜测是这样的:

my_struct.(*my_pointer_to_a_function)(value);

或者应该是

 *my_struct.my_pointer_to_a_function(value);

?

谢谢你。

4

3 回答 3

4

指向函数的指针可以按原样使用,无需任何取消引用:

my_struct.my_pointer_to_a_function(value)

但是,如果您坚持取消引用它,则必须以这种方式使用括号:

(*my_struct.my_pointer_to_a_function)(value)

它们都是完全等价的,所以我推荐第一个,它更简单。

关于你第一次尝试:

my_struct.(*my_pointer_to_a_function)(value); //Error!

那是行不通的,因为括号中的表达式必须首先被评估:*my_pointer_to_a_function,但仅此一点就没有任何意义。

你的第二个:

*my_struct.my_pointer_to_a_function(value); //Error!

运算符优先级规则首先计算.,然后是函数调用,最后是*

*(my_struct.my_pointer_to_a_function(value)); //Error!

因此将调用该函数,但调用的结果 anint将被取消引用,因此会出现错误。

于 2013-07-25T07:48:06.827 回答
2

假设您有指向函数的指针,就像您的结构成员一样:

    struct newtype{
        int a;
        char c;
        int (*f)(struct newtype*);
    } var;
    int fun(struct newtype* v){
        return v->a;
    }

你可以这样称呼它:

    int main(){
        var.f=fun;
        var.f(&var);
     //  ^.....^..... have to pass `var` as an argument to f() :( :(
    }

 //Comment: here in var.f(&var); I miss this pointer and C++,      

所以对于你的情况,它应该只是my_struct.my_pointer_to_a_function(value);

另外几点:
在我的示例中需要注意,即使您想访问必须传递的相同结构变量的成员。(它与 C++ 对象完全不同!)
C++ 类中的虚函数。它们在引擎盖下以类似的方式实现。

这是一个可以帮助您使用的项目:结构中的函数指针

于 2013-07-25T07:47:51.700 回答
-1

用这个:

#define function mystruct.my_pointer_to_a_function

然后你可以调用函数:

int i = function(value);
于 2013-07-25T07:51:08.600 回答