具有两个或更多变量的函数

时间:2016-11-06 15:49:05

标签: c++ c++11 functor

我是C ++ 11的新手,我读了关于仿函数的this帖子,这非常有帮助,我只是觉得有可能制作一个接收多个变量的仿函数吗? 例如,我们有以下课程:

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个或更多(或未知数字!)的变量?

1 个答案:

答案 0 :(得分:1)

是。您可以根据需要传递任意数量的参数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>或模板参数包)。

相关问题