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

C++: overloading the I/O operators

本文关键字:运算符 重载 C++      更新时间:2023-10-16

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

  • 重载运算符<<:无法将左值绑定到"std::basic_ostream&&"
  • 重载运算符<<:无法将"std::basic_ostream"左值绑定到"std::basic_ostream&&"
  • std::ostream {aka std::basic_ostream} Ivalue to 'std::basic_ostream&&
  • 在学习 cpp 上重载 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引用。