c++中的嵌套函数替代

Nested function alternatives in C++

本文关键字:函数 嵌套 c++      更新时间:2023-10-16

我想创建一个函数f(),它使用三个值来计算结果:a, b和e。e依赖于a和b,所以从技术上讲,f()只是a和b的函数。但为了可读性,查看包含抽象e的函数比查看包含许多a和b的更混乱的公式更容易。

是否有任何方法使用因变量像e没有使用嵌套函数,这是c++不允许的?

c++确实有局部变量,这使得这很容易:

double f(double const a, double const b)
{
    double const e = a * b + b * b * b;
    return a + b + e;
}

您可以编写一个局部结构体,它可以定义一个静态函数,它可以像它的嵌套函数一样使用:

int f(int a, int b)
{
   struct local
   {
        static int f(int a, int b, int e)
        {
             return e * (a + b);
        }
   };
   return local::f(a,b, a*b);
}

我不确定我理解你的问题,但如果你只是在一种方法,使你的函数更可读通过引入一个因变量,为什么不只是计算该变量在一个单独的函数调用你的主函数:

float CalculateE(float a, float b)
{
    return (a + b);
}
float f(float a, float b)
{
    float e = CalculateE(a, b);
    return a + b + e;
}

怎么了

int compute_e(int a, int b)
{
    return whatever;
}
int func(int a, int b)
{
    int e = compute_e(a, b);
}

你可以这样做:

int f(int a, int b)
{
    struct LocalFunc
    {
        int operator()(int a, int b)
        {
            return a*b + b*b*b;
        }
    };
    LocalFunc e;
    return e(a,b)*a+b;
}

我想你可以写一些笔记。

int FuncSum(int a, int b)
{
    //return the sum of a + b
    return a + b ;
}