【问题标题】:<< operator not working in C++<< 运算符在 C++ 中不起作用
【发布时间】:2012-10-12 13:01:06
【问题描述】:

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

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

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

【问题讨论】:

  • 请包括第44、45行以及getTitle()的签名

标签: c++ class operators


【解决方案1】:

不看书很难说,但这行得通 [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&lt;&lt; 需要访问非公开数据或函数。你如何声明getTitle()

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2021-05-22
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多