| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 554 人关注过本帖
标题:question about operator= for ostream
只看楼主 加入收藏
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
 问题点数:0 回复次数:1 
question about operator= for ostream

I was aksed to write a program for tutoring the usage of for_each() and ran into the question


os = src.os; // this does not compile


Following is the code (read the comments and try to help me answer the qeustion):

#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

void printFunction(int i)
{
cout<<i<<" ";
}

template<typename T>
struct printFunctor : public unary_function<T, void>
{
printFunctor(ostream& os_=cout) : os(os_), count(0)
{
}

printFunctor<T>& operator= (const printFunctor<T>& src)
{
if(this!=&src)
{
// copyfmt() does the job, but it is not an
// exact copy of the original stream (in src).
//
// Do we have something which is more like
//
// os = src.os;
os.copyfmt(src.os);
count=src.count;

}

return *this;
}

void operator()(const T& x)
{
os<<x<<" ";
++count;
}

ostream& os;
int count;
};

int main()
{
vector<int> v;

v.push_back(1);
v.push_back(2);
v.push_back(4);
v.push_back(8);
v.push_back(16);

for_each(v.begin(), v.end(), printFunction); // &printFunction is ok as well
cout<<endl;

ofstream ofs("out.txt");
if(!ofs)
{
cout<<"cannot open file.\n";
exit(1);
}

/** If we haven't overridden the assignment op, we can use the following syntax:

printFunctor<int> P = for_each(v.begin(), v.end(), printFunctor<int>(cout));
*/

printFunctor<int> P;
printFunctor<int> Q(ofs);

P = for_each(v.begin(), v.end(), P);
cout<<endl<<P.count<<endl;
Q = for_each(v.begin(), v.end(), Q);
ofs<<endl<<Q.count<<endl;

ofs.close();


return 0;
}

[此贴子已经被作者于2007-8-30 6:56:19编辑过]

搜索更多相关主题的帖子: operator question ostream 
2007-08-30 05:56
wfpb
Rank: 6Rank: 6
等 级:贵宾
威 望:29
帖 子:2188
专家分:0
注 册:2006-4-2
收藏
得分:0 
你可以说清楚你的问题吗?不好意思,我在我的编译器上不知道你的代码有什么问题,而且os=src.os编译没有错误啊?

[glow=255,red,2]wfpb的部落格[/glow] 学习成为生活的重要组成部分!
2007-09-02 18:16
快速回复:question about operator= for ostream
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015815 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved