📜  将函数赋值给 C++ 中的变量

📅  最后修改于: 2022-05-13 01:55:48.463000             🧑  作者: Mango

将函数赋值给 C++ 中的变量

在 C++ 中,将函数分配给变量并使用该变量根据用户需要多次调用该函数,可以提高代码的可重用性。以下是相同的语法:

句法:

C++
// Syntax:
  
// Below function is assigned to
// the variable fun
auto fun = [&]() {
    cout << "inside function"
         << " variable";
};


C++
// C++ program to implement function
// assigned to a variable
  
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Below function i.e., is
    // assigned to the variable fun
    auto fun
        = [&]() {
              cout << "Inside Function Variable";
          };
  
    // Call the function using variable
    fun();
  
    return 0;
}


C++
// C++ program to implement parameterized
// function assigned to a variable
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Passing i and j as 2 parameters
    auto fun = [&](int i, int j) {
        cout << "Parameterised Function";
    };
  
    // Call the function using variable
    fun(4, 5);
  
    return 0;
}


C++
// C++ program to implement the function
// assigned to a variable returning
// some values
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Function taking 2 parameters
    // and returning sum
    auto sum = [&](int a, int b) {
        return a + b;
    };
  
    // Call the function using variables
    cout << "The sum is: "
         << sum(4, 5);
  
    return 0;
}


程序 1:下面是实现分配给变量的函数的 C++ 程序:

C++

// C++ program to implement function
// assigned to a variable
  
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Below function i.e., is
    // assigned to the variable fun
    auto fun
        = [&]() {
              cout << "Inside Function Variable";
          };
  
    // Call the function using variable
    fun();
  
    return 0;
}
输出

Inside Function Variable

程序 2:下面是 C++ 程序,用于实现分配给变量的参数化函数:

C++

// C++ program to implement parameterized
// function assigned to a variable
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Passing i and j as 2 parameters
    auto fun = [&](int i, int j) {
        cout << "Parameterised Function";
    };
  
    // Call the function using variable
    fun(4, 5);
  
    return 0;
}
输出
Parameterised Function

方案3:下面是C ++程序来实现分配给一个变量,它返回一个值的函数:

C++

// C++ program to implement the function
// assigned to a variable returning
// some values
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Function taking 2 parameters
    // and returning sum
    auto sum = [&](int a, int b) {
        return a + b;
    };
  
    // Call the function using variables
    cout << "The sum is: "
         << sum(4, 5);
  
    return 0;
}
输出
The sum is: 9
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程