Help wanted on operator overloading

M

Magcialking

template<class T>
ostream& operator<< (ostream& out, const list<T>& lst) {
for (list<T>::const_iterator ref = lst.begin(); ref !=
lst.end();ref++)
/*Compiler says here, ';' shoud occur before ref,and ref is not
declared,but I really don't know what's the problem here*/
out << *ref;
return out;
}
 
M

mimi

"Magcialking дµÀ£º
"
template<class T>
ostream& operator<< (ostream& out, const list<T>& lst) {
for (list<T>::const_iterator ref = lst.begin(); ref !=
lst.end();ref++)
/*Compiler says here, ';' shoud occur before ref,and ref is not
declared,but I really don't know what's the problem here*/
out << *ref;
return out;
}
Have you include the header file <list>.
The following code works fine in my compiler.

#include <list>
#include <iostream>
using namespace std;

template<class T>
ostream& operator<< (ostream& out, const list<T>& lst) {
for (list<T>::const_iterator ref = lst.begin(); ref !=
lst.end();ref++)
std::cout << *ref << "\n";
return out;
}


int main()
{
list<int> a;
a.push_back(1);
cout << a;
return 0;
}
 
M

Magcialking

I'm sure I left nothing.
And the code you give doesn't work in my compliler(Mingw)

"mimi дµÀ£º
"
 
M

Magcialking

I'm sure I left nothing.
And the code you give doesn't work in my compliler(Mingw)

"mimi дµÀ£º
"
 
B

Bo Yang

Magcialking :
template<class T>
ostream& operator<< (ostream& out, const list<T>& lst) {
for (list<T>::const_iterator ref = lst.begin(); ref !=
lst.end();ref++)
/*Compiler says here, ';' shoud occur before ref,and ref is not
declared,but I really don't know what's the problem here*/
out << *ref;
return out;
}
I have compile your code with mingw, and it produce the same
error! The root of the error is that the compiler look
list<T>::const_iterator as a dependent name. So you need to
do

for( typename list<T>::const_iterator ref ...)

and everything is OK!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top