算术操作符重载和关系操作符重载

<pre name="code" class="cpp">#include <iostream>
#include <string>

using namespace std;

class Sales_item
{
public:
	Sales_item(string &book, const unsigned count, const double amount) :isbn(book), units_sold(count), revenue(amount)
	{
	}
	Sales_item& operator+=(const Sales_item&);
	Sales_item& operator-=(const Sales_item&);
	friend std::ostream& operator<<(std::ostream&, const Sales_item&);

	friend bool operator==(const Sales_item&, const Sales_item&); // 关系操作符等于要用友元函数,不等于就不用友元函数,
private:
	string isbn;
	unsigned units_sold;
	double revenue;
};
inline bool operator==(const Sales_item &lhs, const Sales_item &rhs)  // 关系操作符的定义,关系操作符用bool
{
	return lhs.units_sold == rhs.units_sold &&
		lhs.revenue == rhs.revenue &&
		lhs.isbn == rhs.isbn;
}

inline bool operator!=(const Sales_item &lhs, const Sales_item &rhs)  // 不等式操作符不需要进行友元函数定义,
{
	return !(lhs == rhs);
}

// 这个是函数的声明,
Sales_item operator+(const Sales_item&, const Sales_item&);  // 这个是加操作,加的操作不能用引用,它要返回一个新的引用,
Sales_item operator-(const Sales_item&, const Sales_item&); // 这个是函数的声明,是减操作,

Sales_item& Sales_item::operator+=(const Sales_item& rhs)   // 这个是加等于操作,加等于返回的是一个引用,它修改了当前的对象,
{
	units_sold += rhs.units_sold;
	revenue += rhs.revenue;
	return *this;
}

Sales_item& Sales_item::operator-=(const Sales_item& rhs)  // 这个是函数的定义,
{
	this->units_sold -= rhs.units_sold;   // 这里的this-> 可以省略,
	this->revenue -= rhs.revenue;
	return *this;
}


Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs)
{
	Sales_item ret(lhs);
	ret += rhs;
	return ret;
}

Sales_item operator-(const Sales_item& lhs, const Sales_item& rhs)
{
	Sales_item ret(lhs);
	ret += rhs;
	return ret;
}

std::ostream& operator<<(std::ostream& out, const Sales_item& s)
{
	out << s.isbn << "\t" << s.units_sold << "\t" << s.revenue;
	return out;
}

int main()
{
	Sales_item item1(string("0-123-455555-0"), 10, 200.0);
	Sales_item item2(string("0-123-455555-0"), 2, 50.0);
	Sales_item result = item1 + item2;
	cout << result << endl;

	Sales_item item3(string("0-123-455555-0"), 5, 100);
	result += item3;
	cout << result << endl;

	Sales_item item4(string("0-123-455555-0"), 1, 30);
	result -= item4;
	cout << result << endl;


	Sales_item item5(string("0-123-455555-0"), 10, 200.0);
	if (item1 == item5)
	{
		cout << "小崔爱你," << endl;
	}

	if (item1 != item2)
	{
		cout << "不相同," << endl;
	}

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


 
 

你可能感兴趣的:(算术操作符重载和关系操作符重载)