用运算符重载实现分数的加减乘除(c++实现)

此程序运用c++程序中的运算符重载来做。

text.cpp
#include
#include
#include"Score.h"
using namespace std;
int main()
{
	Score a,b,c;
	cout <<"输入三个分数" <>a;
	cin>>b;
	cin>>c;
	a=a+b;
	cout<<"a=a+b的值为:";
	cout <
#ifndef SCORE_H
#define SCORE_H
using namespace std; 
class Score
{
	friend ostream & operator<<(ostream&,     const Score &);
	friend istream & operator>>(istream&,     Score &);
	friend	Score operator+(Score x,Score y);
	friend	Score operator-(Score x,Score y);
	friend	Score operator*(Score x,Score y);
	friend	Score operator/(Score x,Score y);
	public:
		Score(int m=0,int d=0);
		~Score();
	private: 
	int mole;
	int deno;
};

#endif

Score.cpp
#include "Score.h"
#include
#include
using namespace std;
ostream& operator<<(ostream &output,    const Score &sco)
{
	output<< sco.mole << "/" << sco.deno;
	return output; 
}
istream& operator>>(istream &input,    Score &sco)
{
	input>>sco.mole;
	input.ignore(1);                                
	input>>sco.deno;
	return input;
}
Score::Score(int m,int d)
{
	mole=m;
	deno=d;
}
Score operator+(Score x,Score y)
{
	int z;
	int q;
	if(x.deno==y.deno)
	{
		x.mole=x.mole+y.mole;
	}
	z=x.deno;
	q=y.deno;
	while(z%q!=0)
	{
		z=q;
		q=z%q;
	}
	z=x.deno;
	q=y.deno;
	x.deno=x.deno*y.deno/q;
	x.mole=x.mole*(x.deno/z)+y.mole*(x.mole/q);
	return x;
}
Score operator-(Score x,Score y)
{
	int z;
	int q;
	if(x.deno==y.deno)
	{
		x.mole=x.mole-y.mole;
	}
	z=x.deno;
	q=y.deno;
	while(z%q!=0)
	{
		z=q;
		q=z%q;
	}
	z=x.deno;
	q=y.deno;
	x.deno=x.deno*y.deno/q;
	x.mole=x.mole*(x.deno/z)- y.mole*(x.mole/q);
	return x;
}
Score operator*(Score x,Score y)
{
	x.mole=x.mole*y.mole;
	x.deno=x.deno*y.deno;
	return x;
}
Score 	operator/(Score x,Score y)
{
	int z=y.mole;
	y.mole=y.deno;
	y.deno=z;
	x.mole=x.mole*y.mole;
	x.deno=x.deno*y.deno;
	return x;
}
Score::~Score()
{
}

你可能感兴趣的:(用运算符重载实现分数的加减乘除(c++实现))