函数参数vs函数参数的指针? [英] Pointer to function parameter vs function parameter?

查看:152
本文介绍了函数参数vs函数参数的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解以下两个声明之间的区别: f1 f2
f1 我声明这个参数是一个指向 void() f2 声明不同于 f1 ?声明是等效的吗?在 main 中,我可以使用原型 void()的函数调用它们。我理解通过值/指针/引用传递的概念,但是这些是函数,并不真正了解差异。它不像我可以修改作为参数传递的函数在 f1 ...谢谢!

I'd like to understand what is the difference between the 2 declarations, f1 and f2, below: In f1 I declare the parameter to be a pointer to a function of type void(), how is the f2 declaration different from the f1? Are the declarations equivalent? In main I can invoke both of them with functions of prototype void (). I understand the concept of passing by value/pointer/reference, however these are functions and don't really understand the difference. It is not like I can "modify" the function passed as parameter in f1... Thanks!

PS :碰到众所周知的大多数Vexing解析问题时,由这个问题引发的):

PS: came by this question when bumping into the well known Most Vexing Parsing problem :)

#include <iostream>

using namespace std;

void f1(void (*x)())
{
    x();
}

void f2(void x())
{
    x();
}

void g1()
{
    cout << "Invoking f1(g1())" << endl;
}

void g2()
{
    cout << "Invoking f2(g2())" << endl;
}


int main() 
{
    f1(g1);
    f2(g2);
}

程序编译,输出为

Invoking f1(g1())
Invoking f2(g2())


推荐答案

它们是等价的。

由于不能将函数作为参数传递给函数(你不能这样做)任何具有C中函数的函数,除非调用它们或获取它们的地址),编译器会静默地将参数更改为指向函数的指针。

Since you can't pass a function as an argument to a function (you can't do anything with functions in C other than call them or take their address), the compiler silently changes the argument into a pointer to a function.

与数组 - 你不能传递数组作为函数参数,所以任何时候你声明一个函数参数作为数组,它会静静地变成一个指针。

This is much the same as happens with arrays -- you can't pass arrays as function arguments either, so any time you declare a function argument as an array, it silently gets changed into a pointer.

这篇关于函数参数vs函数参数的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆