0

我试图理解 C++ 中的运算符重载,并且可以看到在 + 和 [] 等运算符上仔细使用时的用处。我现在对 () 的重载感兴趣。Boost 似乎将它与它的统计类一起使用,我可以使用它们,但并不真正了解我在做什么。

谁能提供一个简单的例子来说明重载 () 运算符何时有用?谢谢大家皮特

4

2 回答 2

1

重载 operator() 的常见用途是用于函数对象或functors. 您可以使用定义 operator() 的类的对象,并将其用作函数,如下例所示:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class multiply
{
private:
    int x;
public:
    multiply(int value):x(value) { }
    int operator()(int y) { return x * y; }
    int getValue() { return x; }
};

int main()
{
    multiply m(10); //create an object
    cout << "old value is " << m.getValue() << endl;
    int newValue = m(2); //this will call the overloaded () 
    cout << "new value is " << newValue << endl;
}
于 2012-06-09T06:32:20.007 回答
0

简介: 在 C++ 类中重载 () 运算符可以让您实现具有不同类型和参数数量的类方法,为每个方法提供不同的功能。重载 () 时需要小心,因为它的用法没有提供关于正在做什么的线索。它的用途有限,但对于矩阵操作之类的事情可能很有效。

来自:重载 () 运算符 (learncpp.com)

于 2012-06-09T05:53:59.903 回答