如何使“函数调用”重载是有用的。操作员? [英] How can it be useful to overload the "function call" operator?
本文介绍了如何使“函数调用”重载是有用的。操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我最近发现在C ++中你可以重载函数调用运算符,用一种奇怪的方式,你必须写两个括号来这样做:
I recently discovered that in C++ you can overload the "function call" operator, in a strange way in which you have to write two pair of parenthesis to do so:
class A {
int n;
public:
void operator ()() const;
};
然后以这种方式使用:
A a;
a();
这有用吗?
推荐答案
这可用于创建函子,对象的行为类似于函数: / p>
This can be used to create "functors", objects that act like functions:
class Multiplier {
public:
Multiplier(int m): multiplier(m) {}
int operator()(int x) { return multiplier * x; }
private:
int multiplier;
};
Multiplier m(5);
cout << m(4) << endl;
上述输出 20
。上面链接的维基百科文章提供了更多实例。
The above prints 20
. The Wikipedia article linked above gives more substantial examples.
这篇关于如何使“函数调用”重载是有用的。操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文