输入输出操作符重载

#include <iostream>
#include <string>

using namespace std;

class Sales_item
{
friend ostream& operator<<(ostream& out, const Sales_item& s);  // 友元函数,
friend istream& operator>>(istream& in, Sales_item& s);
public:
	Sales_item(string &book, unsigned count, double price) :isbn(book), units_sold(count), revenue(units_sold*price)
	{
	}
	Sales_item() :units_sold(0), revenue(0.0){}  // 初始化,
private:
	string isbn;
	unsigned units_sold;
	double revenue;
};

ostream& operator<<(ostream& out, const Sales_item& s)  // 重载输出操作符,
{
	out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue;
	return out;
}

istream& operator>>(istream& in, Sales_item& s) // 重载输入操作符,
{
	double price;
	in >> s.isbn >> s.units_sold >> price;
	if (in)
		s.revenue = s.units_sold  * price;
	else
		s = Sales_item();
	return in;
}

int main()
{
	Sales_item item(string("0-4500-5"), 2, 31.2);
	cout << item << endl;
	
	cin >> item;
	cout << item << endl;

	cout << "xiao cui" << endl;
	system("pause"); // 暂停,又重新出现一次(请按任意键继续-------)
	return 0;
}

你可能感兴趣的:(输入输出操作符重载)