- 论坛徽章:
- 0
|
近读侯捷先生译的《C++标准程序库》(华中科技大学出版),第五章讲function objects的地方,有点不理解,代码如下(可正常编译执行):
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class AddValue
{
private:
int theValue;
public:
AddValue(int v):theValue(v){}
void operator()(int &elem) const{ elem += theValue; } //这个地方的const
};
int main()
{
list<int> coll;
for (int i=1;i<=9;++i)
coll.push_back(i);
for_each (coll.begin(),coll.end(),AddValue(10)) //这个地方怎么调用的
;
list<int>::const_iterator pos;
for (pos=coll.begin();pos!=coll.end();++pos)
cout << *pos << ' ';
}
想不明白,void operator()(int &elem) const {....}定义为 const 成员函数,那么函数体内不该修改 调用该函数的 对象内的数据成员,这个理解没错吧。
for_each (coll.begin(),coll.end(),AddValue(10)) 中的 AddValue(10)可是个隐式调用?其调用对象是 coll 中的 一个 int 数据成员,按说 const 函数是不该修改 coll中的数据成员的,这里怎么可以修改呢:elem += theValue
请达人帮忙解释一下,谢谢 |
|