類,友元函數 ,重載操作符(+, +=)

#include<iostream>
#include<string>
using namespace std;

class sales_item
{
public:
	friend sales_item add(const sales_item&, const sales_item&);
	friend sales_item operator+(const sales_item&,const sales_item&);

	bool same_isbn(const sales_item& rhs) const
	{
		return isbn == rhs.isbn;
	}

	sales_item(const string& book = ""):isbn(book), units_sold(0), revenue(0.0)
	{

	}

	sales_item(istream& is)
	{
		is >> isbn >> units_sold >> revenue;
	}

	void get_data()
	{
		cout << this->isbn << "," 
			<< this->units_sold << "," 
			<< this->revenue << endl;
	}

	/*定義了操作符()。
	void operator()(istream &is)
	{
	is >> isbn >> units_sold >> revenue;
	}*/


	sales_item operator+(sales_item &obj2)// 注意這裏必須是一個形參。
	{
		if(!obj2.same_isbn(this->isbn))
			return *this;
		sales_item temp = obj2; 
		temp.units_sold = this->units_sold + obj2.units_sold;
		temp.revenue = obj2.revenue + this->revenue;

		return temp;
	}

	sales_item operator+=(sales_item &obj2)
	{
		if(!obj2.same_isbn(this->isbn))
			return *this;
		sales_item &temp = *this; 	//注意:使用引用類型.
		temp.units_sold = this->units_sold + obj2.units_sold;
		temp.revenue = obj2.revenue + this->revenue;
		return temp;
	}

private:
	string isbn;
	unsigned units_sold;
	double revenue; 
};


sales_item add(const sales_item& obj1, const sales_item& obj2)
{
	if(!obj1.same_isbn(obj2))
		return obj1;
	sales_item temp;
	temp.isbn = obj1.isbn;
	temp.units_sold = obj1.units_sold + obj2.units_sold;
	temp.revenue = obj1.revenue + obj2.revenue;
	return temp;
}

sales_item operator+(const sales_item& obj1,const sales_item& obj2)//注意這裏是兩個形參。
{
	if(!obj1.same_isbn(obj2))
		return obj1;
	sales_item temp;
	temp.isbn = obj1.isbn;
	temp.units_sold = obj1.units_sold + obj2.units_sold;
	temp.revenue = obj1.revenue + obj2.revenue;
	return temp;
}


int main()
{
	cout << "Enter two sales_item objects:" << endl;

	sales_item  string1(cin);//這裏調用sales_item(istream&)函數.
	cin.clear();
	sales_item  string2(cin);//這裏調用sales_item(istream&)函數.	


	/*
	上面給string1和string2賦值的方式也可以用下面代碼實現
	sales_item string1, string2;
	string1(cin);//這裏調用operator()。
	cin.clear();
	string2(cin);//這裏調用operator()。	*/


	sales_item sum1 = add(string1, string2);//調用友元函數add函數。
	cout << "調用友元函數add的輸出結果爲:"<< endl;
	sum1.get_data();

	sales_item sum2 = string1 + string2;
	cout << "調用+操作符時的輸出結果:" << endl;
	sum2.get_data();

	sales_item sum3 = string1 + string2;
	cout << "調用+操作符時的輸出結果:" << endl;//調用友元函數。
	sum3.get_data();

	string1 += string2;
	cout << "調用+=操作符時的輸出結果:" << endl;
	string1.get_data();

	return 0;
}

輸出結果如下:


發佈了29 篇原創文章 · 獲贊 10 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章