C++:重载 I/O 运算符

C++: overloading the I/O operators

我是 C++ 的新手,我似乎无法弄清楚重载 I/O 运算符。我已阅读:

但不幸的是,我做错了。我目前的代码如下:

#include <iostream>
#include <string>

// Sales_data structure
struct Sales_data {
  std:: string bookNo;
  unsigned units_sold = 0;
  double revenue = 0.0;
};

// logic to determine if sales data are not equal
bool operator!=(const Sales_data& data1, const Sales_data& data2) {
  // boolen comparision to produce not equal
  return data1.bookNo != data2.bookNo;
}

ostream& operator<< (ostream &out, Sales_data &cSales_data) {
  out << "(" << cSales_data.bookNo << " " << cSales_data.units_sold
      << " " << cSales_data.revenue << ")";
  return out;
}

int main() {
  Sales_data books;  // books is of type sales_data uninitialized
  double price = 0;  // price is of int type initialized at 0
  for (int i = 0; i >= 0; ++i) {
    while (std::cin >> books.bookNo >> books.units_sold >> price) {
      if (books != Sales_data()) {
        i += 1;
        // there is other code here but not relevant to the problem.
        std::cout << books << std::endl;
      }
    }
  }
  return 0;
}

我得到的错误是

 error: ‘ostream’ does not name a type
 ostream& operator<< (ostream &out, Sales_data &cSales_data) {
 ^
exercise2_41a.cpp: In function ‘int main()’:
exercise2_41a.cpp:52:22: error: cannot bind ‘std::ostream {aka
std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
         std::cout << books << std::endl;

我遇到问题的代码是

ostream& operator<< (ostream &out, Sales_data &cSales_data) {
  out << "(" << cSales_data.bookNo << " " << cSales_data.units_sold
      << " " << cSales_data.revenue << ")";
  return out;
}

但我不太确定我需要做什么才能达到预期的结果。我错过了什么?我相信我在正确的轨道上,但这也可能是一场闹剧。

std::ostream& operator<< (std::ostream &out, const Sales_data &cSales_data)

将函数中 ostream 的所有实例替换为 std::ostream。它们是不同的,后者才是你需要的。

可选地,使 operator<<() 的第二个参数接受 const 引用。