我看到在STL容器中使用了 operator()
,但它是什么以及何时使用它?
我看到在STL容器中使用了 operator()
,但它是什么以及何时使用它?
这个运算符将您的对象转换为函数对象。 这里有一个很好的示例。
下一个示例演示了如何实现一个类以将其用作函数对象:
#include <iostream>
struct Multiply
{
double operator()( const double v1, const double v2 ) const
{
return v1 * v2;
}
};
int main ()
{
const double v1 = 3.3;
const double v2 = 2.0;
Multiply m;
std::cout << v1 << " * " << v2 << " = "
<< m( v1, v2 )
<< std::endl;
}
operator()
用途的人不太可能知道什么是函数对象,也不会寻找那个问题。 - Gorpikoperator()
和函数对象之间的关系。 - Troubadour