C++运算符重载的实现

/*

1.怎么实现运算符重载:
1.1 重载的实质:把运算符当作函数去实现另一种功能
1.2 具体实现
函数返回值 operator 运算符(参数)
{
//对复杂操作的打包
}
operator+运算符当作函数

2.运算符的分类
2.1 友元重载
友元函数的形式重载
参数个数等于操作数
2.2 类重载
类的成员函数重载
参数个数=操作数-1

操作数:运算符需要几个数能够使用

3.规则和限制
限制:() [] > 只能以类的成员函数去重载
规则:单目运算符:类重载
双目:友元重载
*/


#include 
using namespace std;

class MM
{
public:
	MM(){}
	MM(int mmx, int mmy)
	{
		this->mmx = mmx;
		this->mmy = mmy;
	}
	MM(MM &mm)
	{
		this->mmx = mm.mmx;
		this->mmy = mm.mmy;
	}

	void print()
	{
		cout << this->mmx << "," << this->mmy << endl;
	}

	void input(istream &in)
	{
		cout << "input:" << endl;
		in >> mmx >> mmy;
	}

	//流重载 <<  >> 友元形式+间接友元
	friend ostream& operator<<(ostream &out, MM &mm);
	friend istream& operator>>(istream &in, MM &mm);

	MM operator+(MM &mm)
	{
		MM tmp;
		tmp.mmx = this->mmx + mm.mmx;
		tmp.mmy = this->mmy + mm.mmy;
		return tmp;
	}


	friend MM operator-(MM &a, MM &b);

private:
	int mmx;
	int mmy;

};

MM operator-(MM &a, MM &b)
{
	MM tmp;
	tmp.mmx = a.mmx - b.mmx;
	tmp.mmy = a.mmy - b.mmy;
	return tmp;
}

ostream& operator<<(ostream &out, MM &mm)
{
	out << "x:" << mm.mmx << "\ty:" << mm.mmy << endl;
	return out;
}
istream& operator >> (istream &in, MM &mm)
{
	mm.input(in);
	return in;
}

int main()
{
	MM minM(100, 200);
	MM maxM(300, 400);
	MM mm = maxM + minM;
	//类重载
	//maxM.operator+(minM);
	//mm.print();
	cout << mm << endl;
	mm = maxM - minM;
	//友元重载
	//operator-(maxM,minM);
	//mm.print();
	cout << mm << endl;

	cin >> mm;
	cout << mm << endl;
	while (1);
	return 0;
}

 

你可能感兴趣的:(C++运算符重载的实现)