类,友元函数 ,重载操作符(+, +=)

#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;
}

输出结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值