输入输出运算符必须是非成员函数
输入时的错误
- 当流含有错误类型的数据时读取操作可能失败。
- 当读取操作到达文件尾或者输入流的其他错误时也会失败。
#include <iostream>
#include <string>
using namespace std;
class Sales_item
{
friend ostream& operator<<(ostream& os, const Sales_item &item);
friend istream& operator>>(istream& is, Sales_item &item);
public:
Sales_item(string &book, unsigned count, double price) :
isbn(book), units_sold(count), revenue(count*price){}
Sales_item() :units_sold(0), revenue(0.0){}
private:
string isbn;
unsigned units_sold;
double revenue;
};
ostream& operator<<(ostream& os, const Sales_item &item)
{
os << item.isbn << " " << item.units_sold << " "
<< item.revenue << " ";
return os;
}
istream& operator>>(istream& is, Sales_item &item)
{
double price;
is >> item.isbn >> item.units_sold >> price;
if (is)
item.revenue = item.units_sold*price;
else
item = Sales_item();
return is;
}
int main()
{
Sales_item item;
cin >> item;
cout << item;
return 0;
}