2012-10-12 7 views
0

저는 이것을 시도해 보려고 많은 노력을했지만 아무것도 해결하지 못하고이 문제를 해결하기 위해 무엇을해야하는지 혼란 스럽습니다.<< 연산자가 C++에서 작동하지 않습니다

std::ostream& operator <<(std::ostream& os, const Book& b){ 
os<<b.getTitle()<<", "<<b.getYear(); 
return os; 
} 

friend std::ostream& operator<<(std::ostream&, const Book&); 

그리고 난이 오류

Book.cc: In function 'std::ostream& operator<<(std::ostream&, const Book&)': 
Book.cc:45: error: no match for 'operator<<' in 'std::operator<< [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((std::basic_ostream<char, std::char_traits<char> >&)((std::basic_ostream<char, std::char_traits<char> >*)os)), ((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >*)(& Book::getTitle() const())))) << ", "' 
Book.cc:44: note: candidates are: std::ostream& operator<<(std::ostream&, const Book&) 

난 정말이 작업을 수행하는 방법에 난처한 상황에 빠진거야가 계속. 도움 주셔서 감사합니다.

+2

줄 44, 45 및'getTitle()'의 서명을 포함하십시오. – Zeta

답변

2

이 책을 보지 않고 말할 어렵지만,이 [code] 작동합니다 : 당신이 비공개 데이터 나 기능에 액세스 할 수 friendoperator<<하지 않는 한 요구를 사용할 필요가 없습니다

#include <string> 
#include <iostream> 

class Book 
{ 
public: 
    const std::string getTitle() const { return "title"; } 
    const std::string getYear() const { return "year"; } 
}; 

std::ostream& operator<< 
(
    std::ostream& os, 
    const Book& b 
) 
{ 
    os << b.getTitle() << ", " << b.getYear(); 
    return os; 
} 

int main() 
{ 
    Book b; 
    std::cout << b << std::endl; 
} 

참고. getTitle()을 어떻게 선언합니까?

관련 문제