2012-12-10 115 views
0

我有一个处理音乐专辑的Classartistsalbumsstrings。它还有一个名为contents的曲目集合(vector)。每个曲目有一个title和一个durationC++ ostream << Operator

这是我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类缺少的东西?

+1

'Album :: getContents()'返回什么? – juanchopanza

+1

getContents返回什么? –

回答

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演示here

+0

+1非常具有解释性和解决方案的代码。 – Stefan

+0

忽略我最后的评论,这是一个错字。不幸的是它说“不能推断自动类型”? – binary101

+0

将循环更改为使用索引或迭代器。 –

0

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

只是超过'<<' operatorvector,你很高兴。