-4

I was going through STL list and I tried to implement the list as type class instead of int or any other data type. Below is the code I tried to compile

#include <iostream>
#include <list>

using namespace std;

class AAA {
public:
    int x;
    float y;
    AAA();
};

AAA::AAA() {
    x = 0;
    y = 0;
}

int main() {
    list<AAA> L;
    list<AAA>::iterator it;
    AAA obj;

    obj.x=2;
    obj.y=3.4;
    L.push_back(obj);

    for (it = L.begin(); it != L.end(); ++it) {
        cout << ' ' << *it;
    }
    cout << endl;
}

But it is giving error in the line:

cout<<' '<<*it;

and the error is

In function 'int main()':
34:13: error: cannot bind 'std::basic_ostream<char>' lvalue to    'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
             from 1:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of    'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT,   _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>;   _Tp = AAA]'
 operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
 ^

Actually I want to print the contents of the list using the code above.Can somebody help me in solving this??

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
NixiN
  • 83
  • 9

1 Answers1

4

You try to output an object of type AAA to a std::ostream. To do that, you need to write an overload for operator<<. Something like this:

std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
    stream << lhs.x << ',' << lhs.y;
    return stream;
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • your suggestion was helpful.Now i am able to get the desired output.It would be a great favour if you explain me how it works. I mean how it called,invoked and from where because I am new to operator overloading. – NixiN Jun 29 '15 at 09:16
  • @NixiN an exhaustive explanation of operator overloading is a bit out of scope for this. I'd suggest having a look at [this question](http://stackoverflow.com/questions/4421706/operator-overloading). – TartanLlama Jun 29 '15 at 09:18