c++中的嵌套函数替代
Nested function alternatives in C++
我想创建一个函数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 ;
}
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何在 C++ 的外部类构造函数中初始化嵌套类成员
- 如何使用 binary_search STL 函数在嵌套类中搜索整数?
- 嵌套模板函数采用 2 个具有相同内部类型的容器
- C++将结构传递给函数以访问嵌套结构
- C++ 在外部使用嵌套结构实现类函数
- 嵌套模板函数的重载
- 通过两个嵌套函数传递C++函数的名称
- 如何从另一个嵌套类中调用某个封闭类的嵌套类的函数指针成员的值?
- MSVC 2017 - 错误 - 如何将模板类 X 的模板成员函数声明为嵌套类 X::Y 的好友
- 使用嵌套函数数组是个好主意吗?
- 嵌套的模板结构构造函数实现
- C2436 '{ctor}':构造函数初始值设定项列表中的成员函数或嵌套类
- 我们可以在main函数中声明嵌套类对象吗
- C++嵌套的迭代器类(在链表类中)Insert_After函数
- 访问另一个类中的模板化嵌套类函数和对象
- Cllass 函数不解析嵌套类实例或函数
- C++析构函数嵌套类的显式模板
- C++和析构函数(嵌套类和一般问题)
- C++函数嵌套模板