函数调用运算符

geo*_*rge 6 c++ stl operator-overloading function-call-operator

可能的重复:
C++ Functors - 及其用途.
为什么要覆盖operator()?

我已经看到了operator()STL容器的使用,但它是什么,你什么时候使用它?

BЈо*_*вић 9

该操作符将您的对象转换为仿函数.这是如何完成的很好的例子.

下一个示例演示如何实现一个类以将其用作仿函数:

#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;
}
Run Code Online (Sandbox Code Playgroud)