简体   繁体   English

指向c ++函数的指针

[英]A pointer to function in c++

When I did something with pointer to function I noticed something and didn't understand 当我用指针指向函数时,我发现了一些东西并且不明白

I did this: 我这样做了:

#include <stdio.h>

int callback(void)
{
   return 5;
}

void call(int (*cpmpare)(void))
{
    int x;
    x = cpmpare();
    printf("%d", x);
}

void main()
{
    int (*compare)(void);
    int *a, b;
    b = 5;
    a = &b;
    compare = callback;
    printf("%p\n", &callback);
    printf("%p\n", compare);
    call(&callback);
}

And I did compare = &callback instead compare = callback and it did the same, compare got the same address as did callback. 我做了compare = &callback而不是compare = callback ,它做了同样的事情,比较得到了与回调相同的地址。

Why did it work both ways? 为什么两种方式都有效?

From what I know comparing a pointer and a regular variable will be wrong. 据我所知,比较指针和常规变量将是错误的。

Functions, like arrays, decay into pointers in some contexts. 函数(如数组)在某些上下文中会衰减为指针。 It's almost always the same to use &function or function . 使用&functionfunction几乎总是一样的。 In your example that's definitely the case. 在你的例子中,情况确实如此。 These two statements are semantically identical: 这两个语句在语义上是相同的:

compare = callback;
compare = &callback;

As are these two: 这两个是:

call(&callback);
call(callback);

Likewise, when you want to use the function pointer, the * is also optional: 同样,当您想使用函数指针时, *也是可选的:

x = cpmpare();
x = (*cpmpare)();

The C committee decided that (since the meaning was unambiguous) that the name of a function (not followed by parens to call the function) would evaluate to the address of the function (in much the same way that the name of an array evaluates to the address of the beginning of the array). C委员会决定(因为含​​义是明确的)函数的名称(没有后跟调用该函数的parens)将计算到函数的地址(与数组的名称求值的方式大致相同)数组开头的地址)。

The official wording is (§C99, 6.3.2.1/4): 官方措辞是(§C99,6.3.2.1/ 4):

A function designator is an expression that has function type. 函数指示符是具有函数类型的表达式。 Except when it is the operand of the sizeof operator or the unary & operator, a function designator with type ''function returning type'' is converted to an expression that has type ''pointer to function returning type''. 除非它是sizeof运算符或一元&运算符的操作数,否则具有类型''函数返回类型''的函数指示符将转换为具有类型''指向函数返回类型'的指针的表达式。

Although I'm not sure Bjarne or the C++ committee was nearly so excited about the idea, they apparently decided to go along with this, so the same remains true in C++. 虽然我不确定Bjarne或C ++委员会对这个想法几乎是如此兴奋,但他们显然决定同意这一点,所以在C ++中也是如此。 The (primary) reason I think they were unenthused about this is that although they could have done the same with the name of a member function that wasn't followed by parens to call that member function, they chose not to -- to get a pointer to a member function, you must use the address-of operator ( & ). 我认为他们对此不感兴趣的(主要)原因是,尽管他们可以使用成员函数的名称进行相同的操作,而该成员函数的名称后面没有parens来调用该成员函数,但他们选择不 - 获取指向成员函数的指针, 必须使用address-of运算符( & )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM