简体   繁体   中英

c++: Printing a STL list

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??

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;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM