2012-12-10 9 views
0

나는 음악 앨범을 다루는 Class이있다. artistsalbumsstrings입니다. 또한 contents 트랙 컬렉션 (vector)이 있습니다. 각 트랙은 titleduration입니다.C++ 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; 
    } 

<<a.getContents() 옆에 밑줄을 말한다되어 "Error: no operator "<<" matches these operands.

내가 무엇을 놓치고 또는 잘못된거야? 이 방법으로 벡터를 사용할 수 있습니까? 아니면 Track 클래스에서 빠진 내용 일 수도 있습니다. Album::getContents() 반환 std::vector<Track> 가정

+1

'Album :: getContents()'는 무엇을 반환합니까? – juanchopanza

+1

'getContents'는 무엇을 반환합니까? –

답변

3

, 당신은

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

데모는 here입니다.

+0

매우 설명적이고 코드로서의 해결책. – Stefan

+0

마지막 코멘트를 무시하고 오타였습니다. 불행히도 그것은 "자동 유형을 추론 할 수 없다"고 말했습니까? – binary101

+0

인덱스 또는 반복기를 사용하도록 루프를 변경하십시오. –

0

Album::getContents() 만약 당신의 벡터에 관한 더 '<<' operator이 없기 때문에 당신은 그것을 작성하는 방법을 모르는 vectorostream보다를 반환합니다.

바로 '<<' operatorvector을 오버로드하면 행복합니다.

관련 문제