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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值