在运算符重载中使用()
use of () in operator overloading
我用operator()找到了这段代码。我以前从未见过(我见过+、>、-<<)。有人能解释一下它应该在什么时候使用以及应该如何使用吗?
class sortResults
{
public:
bool operator() (Result const & a, Result const & b);
};
这被称为函子(不要与函数编程语言中的函子混淆)。
它模仿一个函数,可以在标准库的函数中使用:
std::vector<Result> collection;
// fill with data
// Sort according to the () operator result
sortResults sort;
std::sort(collection.begin(), collection.end(), sort);
与简单的函数相比,一个很好的优势是它可以保存状态、变量等。你可以用闭包(如果这听起来很像)进行并行
struct GreaterThan{
int count;
int value;
GreaterThan(int val) : value(val), count(0) {}
void operator()(int val) {
if(val > value)
count++;
}
}
std::vector<int> values;
// fill fill fill
GreaterThan gt(4);
std::for_each(values.begin(), values.end(), gt);
// gt.count now holds how many values in the values vector are greater than 4
这意味着可以调用sortResults
实例,就像一个函数需要两个Result
参数:
sortResults sr;
Result r1, r2;
bool b = sr(r1, r2);
这样的类被称为"函子"。大多数标准库算法都有重载,它们采用一元或二元函子,比如这个。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板