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

时间:2015-04-25 02:25:10

标签: c++ io operator-overloading

我是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;
}

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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