#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;
}
输出结果如下: