函数对象和构造函数

function objects and constructors

本文关键字:构造函数 对象 函数      更新时间:2023-10-16

我刚刚在读这个

class biggerThan 
      {
        public:
        const int testValue;
        biggerThan(int x) : testValue(x) { }
        bool operator()(int val) const 
        { return val > testValue; }
  };

现在说它像一样使用

  std::list<int>::iterator firstBig =
     std::find_if(aList.begin(), aList.end(), biggerThan(12));

就这么简单biggerThan对象(12)

现在,当使用biggerThan(12)this时,它可以调用constructor来初始化testvalue,或者()运算符被重载,12被传递给函数(bool operator()(int val)const),从而返回bool。

哪一个先发生/它是如何工作的

它是否会导致任何歧义,或者对超长段操作员的呼叫是否以某种方式发生,如

对象.运算符().(12).

请把我的下腰弄清楚。

也许下面的代码会让它变得清晰:

#include <iostream>
#include <algorithm>
class biggerThan 
      {
        public:
        const int testValue;
        biggerThan(int x) : testValue(x) { 
            std::cout << "Construction of biggerThan object with value " 
                      << x << std::endl;
        }
        bool operator()(int val) const 
        { 
            if (val > testValue) {
                std::cout << val << " is bigger than " << testValue 
                          << std::endl;
                return true;
            }
            else {
                std::cout << val << " is *not* bigger than " << testValue 
                          << std::endl;
                return false;
            }
        }
};
int main() {
    int data[] = {0,1,2,3,4,5,6,7,8,9};
    std::for_each(data, data+10, biggerThan(4));
}    

输出为:

Construction of biggerThan object with value 4
0 is *not* bigger than 4
1 is *not* bigger than 4
2 is *not* bigger than 4
3 is *not* bigger than 4
4 is *not* bigger than 4
5 is bigger than 4
6 is bigger than 4
7 is bigger than 4
8 is bigger than 4
9 is bigger than 4

发生了什么:

  1. std::for_each的最后一个参数是类型为biggerThan的对象,该对象是用参数4构造的
  2. 这个biggerThan-对象的operator()(int)(实际上是它的副本)被调用用于data中的每个元素

您使用的算法(std::find_if)在这方面的工作原理相同。

当使用biggerThan(12)时,它可以调用构造函数来初始化testvalue

是的。CCD_ 10创建CCD_ 11类的实例,其中CCD_。

std::find_if()调用函子时,它将调用该实例的operator()(int val)成员函数。

biggerThan(12)将在std::find_if(aList.begin(), aList.end(), biggerThan(12));行传递一个biggerThan对象;

调用operator()的方法如下;

biggerThan obj(12); //This is a constructor call
biggerThan(13); //This is function operator call  

@std::find_if(aList.begin(), aList.end(), biggerThan(12));传递的第三个参数将是temporary object of biggerThan initialized with 12

通常,您可以使用更大的<>以及bind2nd<>,它们在<功能>

list<int>::iterator firstBig = find_if(aList.begin(), aList.end,
                                       bind2nd(greater<int>(), 12));

bind2nd转换任何二进制函数对象,如大于<int>转换为一元函数对象。在大于<int>它有效地创建了一个函数对象,其小于运算符看起来像这个

 bool operator>(const int& arg)
 {
    return functor.operator>(arg, 12); 
 }

其中函子大于<int>