[英]C++ ostream << Operator
I have a Class
that deals with Music Albums. 我有一
Class
处理音乐专辑。 The artists
and albums
are strings
. artists
和albums
是strings
。 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;
}
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.