2012-12-10 117 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,你很高興。