- 论坛徽章:
- 0
|
本帖最后由 ccnuliu 于 2011-05-19 12:38 编辑
- #include<iostream>
- using namespace std;
- #include<string>
- #include<vector>
- struct test
- {
- void operator()(int a)
- {
- cout<<a;
- }
- };
- void fun(test &a)
- {
- a(12);
- }
- struct print
- {
- void operator()(int a)
- {
- cout<<a;
- }
- };
- int main()
- {
- fun(test());
- vector<int> obj;
- obj.push_back(123);
- obj.push_back(456);
- for_each(obj.begin(),obj.end(),print());
- return 0;
- }
复制代码 这里的 void operator()(int a) const 和void fun(const test &a)
为啥一定要加const,不然编译不过。
foreach.cpp: In function `int main()':
foreach.cpp:27: error: invalid initialization of non-const reference of type 'test&' from a temporary of type 'test'
foreach.cpp:13: error: in passing argument 1 of `void fun(test&)'
而给for_each的void operator()(int a)却不需要加const?- template<class _InIt,
- class _Fn1> inline
- _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
- { // perform function for each element
- _DEBUG_RANGE(_First, _Last);
- _DEBUG_POINTER(_Func);
- _CHECKED_BASE_TYPE(_InIt) _ChkFirst(_CHECKED_BASE(_First));
- _CHECKED_BASE_TYPE(_InIt) _ChkLast(_CHECKED_BASE(_Last));
- for (; _ChkFirst != _ChkLast; ++_ChkFirst)
- _Func(*_ChkFirst);
- return (_Func);
- }
复制代码 |
|