0

我有一个Class处理音乐专辑的。artistsalbumsstrings。_ 它还有一个名为 ( vector) 的曲目集合contents。每个轨道都有一个title和一个duration

这是我的ostream <<

    ostream& operator<<(ostream& ostr, const Album& a){
        ostr << "Album: "    << a.getAlbumTitle() << ", ";
        ostr << "Artist: "   << a.getArtistName() << ", ";
        ostr << "Contents: " << a.getContents()   << ". "; //error thrown here
        return ostr;
    }

<<旁边的下划线a.getContents()表示:"Error: no operator "<<" matches these operands.

我错过了什么或做错了什么?你不能用这种方式使用向量吗?或者也许是我在 Track 课上缺少的东西?

4

2 回答 2

3

假设Album::getContents()退货std::vector<Track>,您需要提供

std::ostream& operator<<(std::ostream& o, const Track& t);

std::ostream& operator<<(std::ostream& o, const std::vector<Track>& v);

后者可以使用前者。例如:

struct Track
{
  int duration;
  std::string title;
};

std::ostream& operator<<(std::ostream& o, const Track& t)
{
  return o <<"Track[ " << t.title << ", " << t.duration << "]";
}

std::ostream& operator<<(std::ostream& o, const std::vector<Track>& v)
{
  for (const auto& t : v) {
    o << t << " ";
  }
  return o;
}

这里有一个 C++03 演示。

于 2012-12-10T20:50:55.607 回答
0

如果Album::getContents()是关于你的向量,你只是返回vectorostream不知道如何写它,因为没有'<<' operator.

只需超载'<<' operatorfor a vector,您就会很高兴。

于 2012-12-10T20:53:25.660 回答