C++-重載操作符> = + - * /

以代碼爲例,重載了<< >>  = + - * /

/************************************************************************/
/*    功能:分數類                                                      */
/*    描述:支持+ - * /                                                 */
/************************************************************************/

#include <iostream>

using namespace std;
////////////////////////////類申明//////////////////////////////////////
class Fraction{
private:
	int m;
	int z;
public:
	Fraction(int z = 1, int m = 1):z(z), m(m){}		//默認構造函數
	Fraction(const Fraction & F):z(F.z), m(F.m){}	//拷貝構造函數
	~Fraction(){}
	//(重載類型一)友元函數:友元函數中可以調用該類的私有變量
	friend istream& operator>>(istream& in, Fraction & F);
	friend ostream& operator<<(ostream& out, Fraction & F);
	//(重載類型二)使用引用做返回值:可以像cout與cin一樣流操作
	Fraction & operator =( const Fraction & f);
	//(重載類型三) 一般重載:重載了+-*/,重點是學習重載,所以不考慮算法
	Fraction  operator +( const Fraction & f);
	Fraction  operator -( const Fraction & f);
	Fraction  operator *( const Fraction & f);
	Fraction  operator /( const Fraction & f);
};
////////////////////////////類的實現//////////////////////////////////////
Fraction&  Fraction::operator=(const Fraction & f)
{
	this->z = f.z;
	this->m = f.m;
	return *this;
}
Fraction  Fraction::operator +( const Fraction & f)
{
	Fraction temp;
	temp.z = this->z + f.z;
	temp.m = this->m + f.m;
	return temp;
}

Fraction  Fraction::operator -( const Fraction & f)
{
	Fraction temp;
	temp.z = this->z - f.z;
	temp.m = this->m - f.m;
	return temp;
}
Fraction  Fraction::operator *( const Fraction & f)
{
	Fraction temp;
	temp.z = this->z * f.z;
	temp.m = this->m * f.m;
	return temp;
}
Fraction  Fraction::operator /( const Fraction & f)
{
	Fraction temp;
	temp.z = this->z / f.z;
	temp.m = this->m / f.m;
	return temp;
}
//////////////////////////全局函數////////////////////////////////////////
ostream& operator<<(ostream& out, Fraction & F)
{
	out<<F.z<<"/"<<F.m;
	return out;
}
istream& operator >>(istream& in, Fraction & F)
{
	char c;
	in>>F.z>>c>>F.m;
	if (c == '/')
	{
		return in;
	}else{
		cout<<"輸入錯誤"<<endl;
		F.m = 1;
		F.z = 1;
		return in;
	}
}

////////////////////////////測試函數//////////////////////////////////////
int main()
{
	Fraction a,b,c,d,e,f,g(2,3);

	cout<<"(test <<     )Please enter a fraction: a = ";
	cin>>a;
	b = a;
	cout<<"(test >> =  )   b = a         :  b = "<<b<<endl;
	c = a + b;
	cout<<"(test >> = +)   c = a + b     :  c = "<<c<<endl;
	d = c - b;
	cout<<"(test >> = -)   d = c - b     :  d = "<<d<<endl;
	e = a * b;
	cout<<"(test >> = *)   e = a * b     :  e = "<<e<<endl;
	f = e / g;
	cout<<"(test >> = /)   f = e / (2/3);:  f = "<<f<<endl;

	system("pause");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章