我有点新的C ++ 11和我读到这一篇关于仿函数,这是非常有帮助的,我只是认为这是有可能使这不是一个变量接收更多的是仿函数?例如,我们有下面的类:
class my_functor{
public:
my_functor(int a,int b):a(a),b(b){}
int operator()(int y)
{
return a*y;
}
private:
int a,b;
};
现在我想知道有什么方法可以使成员函数像
operator()(int y)
但是收到2个或更多(或未知数!)的变量?
是的。您可以根据需要传递任意数量的参数operator()
。参见例如:
#include <iostream>
class my_functor{
public:
my_functor(int a,int b):a(a),b(b){}
int operator()(int y)
{
return a*y;
}
int operator()(int x, int y)
{
return a*x + b*y;
}
private:
int a,b;
};
int main()
{
my_functor f{2,3};
std::cout << f(4) << std::endl; // Output 2*4 = 8
std::cout << f(5,6) << std::endl; // Output 2*5 + 6*3 = 28
return 0;
}
要处理未知数量的参数,您需要查看用于处理可变数量的参数(基本上是#include <varargs.h>
,或模板参数包)的各种解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句