#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
//函数对象做参数 做返回值
class myprint04{
public:
myprint04() :count(0){}
void operator()(int v){
count++;
cout << v << " ";
}
int count;
};
void test04(){
vector<int> v;
for (int i = 0; i < 10;i++){
v.push_back(i);
}
myprint04 myp04;
myprint04 myp05 = for_each(v.begin(), v.end(), myp04); //函数对象做参数
cout << "count:" << myp04.count << endl; cout << endl;
cout << "count:" << myp05.count << endl; cout << endl;
}
int main(){
test04();
return 0;
}
0 1 2 3 4 5 6 7 8 9 count:0
count:10
我不理解的是myp04.count为什么是0.既然是0,我断点调试也发现对象成员
变量的值的确没变。可是不知道为什么,谁能说一下原理吗
在你的代码中写一个拷贝构造函数就明了
myprint04(const myprint04& s) {
cout << "copy" << endl;
count = s.count;
}
看for_each的源码
template<class _InIt,
class _Fn> inline
_Fn for_each(_InIt _First, _InIt _Last, _Fn _Func)
{ // perform function for each element [_First, _Last)
_DEBUG_RANGE(_First, _Last);
auto _UFirst = _Unchecked(_First);
const auto _ULast = _Unchecked(_Last);
for (; _UFirst != _ULast; ++_UFirst)
{
_Func(*_UFirst);
}
return (_Func);
}
参数列表中的 _Fn _Func不是引用,会调用默认拷贝函数,所以在for_each中的myp04不是你之前定义的myprint04 myp04;
在函数结束返回的时候再次调用默认拷贝函数给myp05赋值
这样就是了