c ++中的函子示例

时间:2018-03-29 17:05:07

标签: c++ functor

// this is a functor
struct add_x {
  add_x(int x) : x(x) {}
  int operator()(int y) const { return x + y; }

private:
  int x;
};

.........................................

在上面的仿函数定义中,我无法解释该行

add_x(int x) : x(x) {}

请有人从基本解释。 或提供源(视频讲座或文本阅读),以便我理解它的语法和工作。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可能会感到困惑,因为成员变量名称(x)与函数参数(也是x)相同,为了清楚起见,您始终可以避免这一点。简化的代码可以是这样的。

add_x(int x1) : x(x1)  // a contructor that initializes the member vaiable x to x1
{  
}

仍然困惑?然后你可以去做(尽管不是那么优化)

add_x(int x1) 
{  
   x = x1;
}

答案 1 :(得分:0)

这是一个构造函数

这不是标准的功能/方法。每个类(struct)都可以有构造函数。构造函数与类具有相同的名称,并且可以选择使用参数。

struct add_x {
    int x;
    add_x(int x) : x(x) {}   // This is a constructor with one paramter
};

为了便于阅读,让我们更好地格式化。

struct add_x {
    int x;
    add_x(int x)    // Constructor that takes one argument.
        : x(x)      // This is called the initializer list.
    {}              // This is the body of the constructor.
};

初始化列表允许您列出成员变量(以逗号分隔)并在执行构造函数体之前初始化它们。

在这种情况下,使用参数x初始化成员x

#include <iostream>
int main()
{
    add_x   test(5);
    std::cout << test.x << "\n"; // Should print 5
                                 // Note in my example I have removed the private
                                 // section so I can read the value x.
}