c++小问题

kongzhitai 2010-08-10 09:58:28
8#include <iostream>
9#include <vector>
10#include <iostream>
11#include <algorithm>
12
13using namespace std;
14
15struct printElem {
16 const char* _prefix;
17
18 printElem(const char* prefix) : _prefix(prefix) {}
19
20 void operator() (int elem) {
21 cout << _prefix << elem << endl;
22 }
23};
24
25int main() {
26 int ia[] = {1, 2, 3};
27 vector<int> ivec(ia, ia + sizeof(ia) / sizeof(int));
28
29 for_each(ivec.begin(), ivec.end(), printElem("Element:"));
30}
最后一行那个printElem("Element:")不是只对构造函数的调用吗,里面那个()是怎么调用的
...全文
73 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
mskmc_mc 2010-08-10
  • 打赏
  • 举报
回复
15struct printElem {
16 const char* _prefix;
17
18 printElem(const char* prefix) : _prefix(prefix) {}
19
20 void operator() (int elem) {
21 cout << _prefix << elem << endl;
22 }
23};


printElem(const char* prefix)这是构造,用一个字符串来构造
void operator() (int elem) 这是()重载,用一个int类型来调用
printElem pobj("abcd");这是调用构造
pobj(1);
pobj(2);
popb(3);这些是调用重载操作符()


for_each(ivec.begin(), ivec.end(), printElem("Element:"));
这是一个泛型算法,把ivec从头到尾应用在printElem对象上
实例化后的底层应该是
vector<int>::iterator it=ivec.begin(),end_it=ivec.end();
for(;it!=end_it;++it)
printElem(*it);
这时候调用了重载操作符()
即,cout << _prefix << elem << endl;
_prefix是"Element:"
elem是*it
cougar0709 2010-08-10
  • 打赏
  • 举报
回复
这个是不是就是将"Element:"传给printElem(const char* prefix)里面的参数,期待高手解答
kongzhitai 2010-08-10
  • 打赏
  • 举报
回复
肯定有的,不然写成这样干啥,C++ PRIMER也只说STURCT 和PUBLIC 就是一个访问权限的问题而已
Jim_King_2000 2010-08-10
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 shihuaicheng 的回复:]

struct没有构造函数的概念
[/Quote]
有的。在C++中,struct就是类,只不过默认权限是public。
嘎文 2010-08-10
  • 打赏
  • 举报
回复
struct没有构造函数的概念
kongzhitai 2010-08-10
  • 打赏
  • 举报
回复
我不会连仿函数是什么都不知道的都函数适配器了哦
taodm 2010-08-10
  • 打赏
  • 举报
回复
楼主google “functor”

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧