0

我已经尝试了很多事情来尝试让它工作,但没有任何效果,我真的很困惑我必须做些什么来解决这个问题。

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&)

我真的很困惑如何做到这一点。谢谢您的帮助。

4

1 回答 1

2

没有看到书很难说,但这有效[代码]

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

friend请注意,除非operator<<需要访问非公开数据或函数,否则您不需要使用。你怎么申报getTitle()

于 2012-10-12T13:06:50.043 回答