[英]C++ ostream << Operator
我有一Class
处理音乐专辑。 artists
和albums
是strings
。 它还具有称为contents
的音轨集合( vector
)。 每个曲目都有一个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课上缺少的东西?
假设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的演示在这里 。
如果Album::getContents()
与您的向量有关,而您只是返回vector
,则ostream
不知道如何编写vector
,因为没有'<<' operator
。
只需为vector
重载'<<' operator
,您就会很高兴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.