Istream_iterator类==和!=重载是错误的 [英] Istream_iterator class == and!= overloading is wrong

查看:79
本文介绍了Istream_iterator类==和!=重载是错误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;

template<class In,class Out>
Out copy1(In start,In end,Out dest)
{
while(start!=end){
*dest++=*start++;
}
return dest;
}

template<class T>
class ostream_iterator{
public:
ostream_iterator(ostream& os,const char*s):strm(&os),str(s){}
ostream_iterator& operator++(){return *this;}
ostream_iterator& operator++(int){return *this;}
ostream_iterator& operator*(){return *this;}
ostream_iterator& operator=(const T &t){
*strm<<t<<str;
return *this;
}
private:
ostream* strm;
const char *str;
};

template<class T>
class istream_iterator{
friend int operator==<>(istream_iterator&,istream_iterator&);
friend int operator!=<>(istream_iterator&,istream_iterator&);
public:
istream_iterator(istream& is):strm(&is),full(0),eof(0){}
istream_iterator():strm(0),full(0),eof(1){}
istream_iterator& operator++(){
full=0;
return *this;
}
istream_iterator operator++(int){
istream_iterator r=*this;
full=0;
return r;
}
T operator*(){
fill();
assert(full);
return buffer;
}

private:
T buffer;
istream *strm;
int full;
int eof;
void fill(){
if(!full&&!eof){
if(*strm>>buffer)full=1;
else eof=1;
}
}
};

template<class T>
int operator==(istream_iterator<T>& p,istream_iterator<T>& q)
{
if(p.eof&&q.eof)return 1;
if(!p.eof&&!q.eof)return &p==&q;
p.fill();
q.fill();
return p.eof==q.eof;
}
template<class T>
int operator!=(istream_iterator<T>& p,istream_iterator<T>& q)
{
return !(p==q);
}

int main()
{
ostream_iterator<int> output(cout,"\n");
istream_iterator<int> input(cin);
istream_iterator<int> e;
copy1(input,e,output);
system("pause");
return 0;
}





Istream_iterator类==和!=重载错误。请帮帮我,谢谢!!



Istream_iterator class == and!= overloading is wrong.Please help me,thank you!!

推荐答案

错误是您尝试获取两个引用变量的地址并进行比较。



& p 是一个记忆位置,& q 是另一个内存位置。这个& p ==& q 总是返回false,除非在下面使用你的==运算符的情况下。



if(a == a)。 ( a istream_iterator 类型的对象。



如果你想比较2个整数变量( p q ),请使用以下代码而不是你的行代码。



The error is that you try to get the addresses of two reference variables and compare them.

&p is a memory location and &q is another memory location. This, &p==&q, always returns false except in the following case of using your == operator.

if(a == a). (a is an object of type istream_iterator).

If you want to compare the 2 integer variables (p and q), use the following instead of your line of code.

if(!p.eof && !q.eof)return p==q;


这篇关于Istream_iterator类==和!=重载是错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆