【问题标题】:c++ void function as parameter for other function [closed]c ++ void函数作为其他函数的参数[关闭]
【发布时间】:2021-07-30 12:43:19
【问题描述】:

我不明白为什么这段使用 int 函数和参数的代码可以正常工作,但其他带有 void 函数和不带参数的代码却不能:

第一:

#include <iostream>
int Add(int x, int y)
{
    return x+y;
}
int operation(int x, int y, int (*function)(int, int))
{
    return function(x, y);
}
int main()
{
    std::cout << operation(1, 4, &Add) << std::endl;
    return 0;
}

第二:

#include <iostream>
void a()
{
    std::cout << "something" << std::endl;
}
void b(void (*function))
{
   function();
}
int main()
{
    b(&a);
    return 0;
}

【问题讨论】:

    标签: c++ function arguments void


    【解决方案1】:

    在您的第一个示例中,您不需要获取 Add() 的地址。按名称传递函数,不带参数,将自动获取地址。

    std::cout << operation(1, 4, Add) << std::endl;
    

    在您的第二个示例中,您忘记了函数指针中的括号:

    void b(void (*function)(/* these brackets were missing */))
    {
    

    你也不需要在传递给b时获取a的地址,因为引用一个没有参数的函数会获取它的地址:

    int main()
    {
        b(a);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 2014-04-04
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多