【问题标题】:C++ : how to define a function in main and then pass it as an argumentC++:如何在 main 中定义一个函数,然后将其作为参数传递
【发布时间】:2021-09-01 12:30:24
【问题描述】:

首先,我想在 main 中创建一个函数。其次,我想将此函数作为参数传递给另一个函数。请问可以吗?

对于第一点,我知道可以使用 lambda 函数或结构,如以下链接中所述:Can we have functions inside functions in C++?

但是,我没有设法将此函数作为参数传递给另一个函数。

更准确地说,我想要这样的东西:

int main()
{
    void add(int x, int y){cout<<x+y<<endl;}
    int a = 1;
    int b = 2;
    apply_operator(add,a,b);
}

其中 apply_operator 在另一个文件中定义:

void apply_operator(void (*operator)(int,int),int x,int y)
{
    operator(x,y);
}

【问题讨论】:

  • 我确定 apply_operator 没有像你说的那样定义,因为 operator 是 C++ 关键字。
  • 不能在另一个函数中声明或定义一个函数。你能做的最好的就是 lambda。

标签: c++ main


【解决方案1】:

使用 lambdas 并避免使用我们得到的 operator 关键字:

#include <iostream>

void apply_operator(void (*op)(int, int), int x, int y)
{
    op(x, y);
}

int main()
{
    auto add = [](int x, int y) { std::cout << (x + y) << std::endl; };
    int a = 1;
    int b = 2;
    apply_operator(add, a, b);
}

按预期打印3

【讨论】:

  • 非常感谢,效果很好。我用“apply_operator(&add, a, b);”尝试了同样的事情相反,它没有工作。
  • 这是因为 lambda 已经可以转换为函数指针。获取它的地址会给你一些不同的东西。
【解决方案2】:

你当然可以使用 lambda。

int main()
{
    auto add = [](int x, int y){cout<<x+y<<endl;};
    int a = 1;
    int b = 2;
    apply_operator(add,a,b);
}

See it work!

【讨论】:

  • 非常感谢,效果很好。我用“apply_operator(&add, a, b);”尝试了同样的事情相反,它没有工作。
  • @ZZZ 这是因为无捕获 lambda 将隐式转换为函数指针。您的 lambda 地址不会。
【解决方案3】:

您可能对在这种情况下使用 lambda 感兴趣

int main()
{
    auto add = [](int x, int y){ cout<<x+y<<endl; };
    int a = 1;
    int b = 2;
    apply_operator(add,a,b);
}

只要 lambda 不捕获它就可以衰减为函数指针。

【讨论】:

    【解决方案4】:

    您可以使用函数指针。我已经粘贴了下面的代码。我已经声明了一个指向函数的指针“f”,它接受两个整数并且不返回任何内容,并将函数的地址分配给它。

    #include <iostream>
    
    using namespace std;
    
    void add(int x, int y)
    {
        cout<<x+y<<endl;
    }
    
    void apply_operator(void (*f)(int, int),int a, int b)
    {
        f(a, b);
    }
    int main()
    {
        void (*f)(int, int);
        f = &add;
        int a = 1;
        int b = 2;
        apply_operator(f,a,b);
    }
    

    【讨论】:

      【解决方案5】:
      # include<iostream>
      
      # include<conio.h>
      using namespace std;
      int fun(int a, int b)
      {
          if(a>b)
          {
          cout<<"1st number is larger";
          }
          else
          {   
          cout<<"2nd number is larger";
          }
      }       
      
      int main()
      {
          int a,b;
          cout<<"enter the two numbers";
          cin>>a>>b;
          fun(a,b);
          getch();
      
         return 0;
      
          getch();
      
      }
      

      【讨论】:

      • 我看不出这与这个问题有什么关系。
      猜你喜欢
      • 2012-04-16
      • 2020-02-10
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多