简体   繁体   English

C ++ ostream <<运算符

[英]C++ ostream << Operator

I have a Class that deals with Music Albums. 我有一Class处理音乐专辑。 The artists and albums are strings . artistsalbumsstrings It also has a collection ( vector ) of tracks called contents . 它还具有称为contents的音轨集合( vector )。 Each track has a title and a duration . 每个曲目都有一个title和一个duration

This is my ostream << : 这是我的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;
    }

The << next to the a.getContents() is underlined and says: "Error: no operator "<<" matches these operands. a.getContents()旁边的<<带下划线,并说: "Error: no operator "<<" matches these operands.

What am I missing out or doing wrong? 我错过了什么或做错了什么? Can you not use vectors in this way? 您不能以这种方式使用向量吗? or maybe its something I'm missing from my Track class? 还是我的Track课上缺少的东西?

Assuming Album::getContents() returns std::vector<Track> , you need to provide 假设Album::getContents()返回std::vector<Track> ,则需要提供

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

and

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

where the latter can use the former. 后者可以使用前者。 For example: 例如:

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

There's a C++03 demo here . 有一个C ++ 03的演示在这里

If Album::getContents() is about your vector and you just return the vector than ostream does not know how to write it, because there is no '<<' operator . 如果Album::getContents()与您的向量有关,而您只是返回vector ,则ostream不知道如何编写vector ,因为没有'<<' operator

Just overload the '<<' operator for a vector and you are happy. 只需为vector重载'<<' operator ,您就会很高兴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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