<<运算符不在C ++中工作

时间:2012-10-12 13:01:06

标签: c++ class operators

我已经尝试了许多尝试让它发挥作用,但没有任何作用,我真的很困惑我必须做些什么来解决这个问题。

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

我真的很难过如何做到这一点。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

没有看到Book就很难说,但这有效 [code]

#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()