与圆括号和运算符 () 一起使用的结构名称
Struct name used with round brackets and operator()
我在BOOST中使用了一些数值积分包(见下面的代码)。任何人都可以解释以下含义:
double operator()(double x) {return x/std::log(x);}
这个"运算符()(双倍x)"是什么?
quadrature::adaptive()(f(), 0., 1., answer, error_estimate);
这里的"f()"是什么?
#include <boost/numeric/quadrature/adaptive.hpp>
#include <boost/numeric/quadrature/kronrodgauss.hpp>
#include <iostream>
#include <cmath>
namespace quadrature=boost::numeric::quadrature;
struct f
{
double operator()(double x) const { return x/std::log(x); }
};
int main()
{
double answer, error_estimate;
// integrate x/log(x) on [0,1]
quadrature::adaptive()(f(), 0., 1., answer, error_estimate);
std::cout << "integtral(x/log(x)) on [0,1] is " << answer
<< " with error estimate " << error_estimate
<< std::endl;
return EXIT_SUCCESS;
}
f
是一个函子,即定义operator()
的类(或结构,在这种情况下)。这意味着此类的实例可以像函数一样使用:
f myinstance;
myinstance(2.3);
operator()
定义了f
实例用作函数时的签名和行为,即它提供了将myinstance
应用于参数时执行的实际函数的定义。
f()
的意思是:使用默认构造函数创建f
的匿名实例。 即它的工作方式与上面示例中的f myinstance
类似,只是创建的实例没有名称。
如您所见,f
的实例作为参数传递给adaptive
调用。在内部,此实例随后作为函数应用于各种对象。换句话说,整个机制使您能够定义一个函数(以像f
这样的函子的形式)并将其作为参数传递。
operator()
是C++函数调用运算符。 这意味着您可以将参数括号应用于类的对象,然后调用该运算符。
关于f()
,大概这是您在下面显示的struct f
的实例化。
你需要一本 C++ 教科书
相关文章:
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 尝试将指针与结构一起使用时出错
- OOP使用不同的结构与孩子一起构建建议
- 实现具有浮点键的类似哈希表的数据结构,其中公差内的值被合并在一起
- 为什么当我尝试将priority_queue与参数一起使用作为指向结构的指针时会弹出错误
- 如何将 C# 文本框输入与 C 结构和导入一起使用
- 如何将unordered_set与自定义结构一起使用?
- 将 OpenGL VBO 与自定义类/数据结构一起使用
- CMake 项目结构:如何正确地将库合并在一起并将它们包含在多个可执行文件中
- 将 STL 容器与结构一起使用
- 有关将智能指针与 Winsock 的 addrinfo 结构一起使用的问题
- 将initalizer列表与从空基类继承的结构一起使用
- 如何与CUDA中的结构内部结构一起工作
- 基于PHP示例,与C 中数据结构一起工作的多态性示例
- 与向量和结构一起工作
- 为什么C 11支撑初始化与基于堆栈的类层次结构一起起作用
- 如何将"<<"与我自己的结构一起使用?
- 将向量与结构一起使用
- 将 std::vector 与结构一起使用时出现不完整的类型错误
- 将libuv与函数结构一起使用,而不是函数回调