函数对象和构造函数
function objects and constructors
我刚刚在读这个
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
发生了什么:
std::for_each
的最后一个参数是类型为biggerThan
的对象,该对象是用参数4
构造的- 这个
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>
- 对象实例化调用构造函数的次数太多
- Arduino C++在构造函数中用参数声明对象数组
- 模板,函数使用错误的构造函数来复制我的对象
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 通过构造函数创建的所有对象都具有相同的向量
- 是什么让放置新调用对象的构造函数?
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++ 对象指针数组的复制构造函数
- 在构造函数中输入对象时C++类成员作用域
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- 如何将我编写的对象传递到另一个类的构造函数中?
- 使用向量初始化参数化构造函数的对象数组
- 在C++中将对象从另一个类传递到另一个类的构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 构造函数对象赋值是否泄漏内存
- gcc中不可移动构造函数对象的std::函数