I am asked to write an iterator with the same function as istream_iterator, and the iterator's name is CMyistream_iterator. I want to set up the function of * operator as it is used in iterators.
template<class T>
class CMyistream_iterator{
public:
T my;
T* cm;
CMyistream_iterator(istream& x):my(x){};
T operator * (CMyistream_iterator<T>& p);
};
template<class T>
T CMyistream_iterator<T>::operator * (CMyistream_iterator<T>& p){return p.my;}
int main()
{
CMyistream_iterator<int> inputInt(cin);
int n1,n2,n3;
n1 = * inputInt;
}
But the code goes wrong and saying that" no match for 'operator*'(operand type is CMyistream)". Could anyone help me?
You problem is not related to templates, but to basics of operator overloading. You need to write simply
T operator * ();
and
T CMyistream_iterator<T>::operator * (){
return my; // meaning this->my
}
The reason is that as your operators are already class members, they already have one implicit parameter — the class object itself, and this is the parameter you need to use.
The code as you wrote it declares not indirection operator ( *x
) , but multiplication operator ( x*y
).
Another problem in your code is that you are trying to convert istream
to int
in CMyistream_iterator(istream& x):my(x){};
, but that's unrelated to the compilation error you mentioned; and the solution of this problem depends on what exactly you need to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.