【问题标题】:c++: Printing a STL listc++:打印 STL 列表
【发布时间】:2015-06-29 08:51:31
【问题描述】:

我正在浏览 STL 列表,并尝试将列表实现为类型类而不是 int 或任何其他数据类型。下面是我尝试编译的代码

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

但它在该行中给出错误:

cout<<' '<<*it;

错误是

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)
 ^

实际上我想使用上面的代码打印列表的内容。有人可以帮我解决这个问题吗??

【问题讨论】:

  • 打印使用 coutxy;
  • 我已经尝试过 (*it).x 并且它很有用,但是还有另一种方法可以通过循环打印列表,我的意思是我想避免打印每个单个元素
  • 这与list没有任何关系,尝试简化你的代码,你会从AAA obj; std::cout &lt;&lt; obj;得到同样的错误

标签: c++ list stl iterator


【解决方案1】:

您尝试将AAA 类型的对象输出到std::ostream。为此,您需要为operator&lt;&lt; 编写重载。像这样的:

std::ostream& operator<< (std::ostream& stream, const AAA& lhs)
{
    stream << lhs.x << ',' << lhs.y;
    return stream;
}

【讨论】:

  • 您的建议很有帮助。现在我能够获得所需的输出。如果您向我解释它是如何工作的,那将是一个很大的帮助。我的意思是它是如何调用、调用以及从哪里调用的,因为我是运算符重载的新手。
  • @NixiN 对运算符重载的详尽解释有点超出了这个范围。我建议看看this question
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 2018-06-25
  • 2019-04-26
相关资源
最近更新 更多