c++运算符重载(有理数加减乘除)

// ConsoleApplication11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include
#include
//#include
class Rational
{
public:
	Rational(int num, int denom);
	Rational operator+(Rational rhs);
	Rational operator-(Rational rhs);
	Rational operator*(Rational rhs);
	Rational operator/(Rational rhs);
	void print();
private:
	void normalize();
	int numerator;
	int denominator;
};

Rational::Rational(int num, int denom)
{
	numerator = num;
	denominator = denom;
	normalize();
}


//标准化
void Rational::normalize()
{
	if (denominator < 0)
	{
		numerator = -numerator;
		denominator = -denominator;
	}

	//求出分子和分母的最大公约数,用欧几里得算法
	int a = abs(numerator);
	int b = abs(denominator);
	while (b>0)
	{
		int t = a%b;
		a = b;
		b = t;
	}
	numerator /= a;
	denominator /= a;
}

Rational Rational::operator+(Rational rhs)
{
	int a = numerator;
	int b = denominator;
	int c = rhs.numerator;
	int d = rhs.denominator;
	int e = a*b + c*d;
	int f = b*d;
	return Rational(e, f);
}

Rational Rational::operator-(Rational rhs)
{
	rhs.numerator = -rhs.numerator;
	return operator+(rhs);
}

Rational Rational::operator*(Rational rhs)
{
	int a = numerator;
	int b = denominator;
	int c = rhs.numerator;
	int d = rhs.denominator;
	int e = a*c;
	int f = b*d;
	return Rational(e, f);
}

Rational Rational::operator/(Rational rhs)
{
	int t = rhs.numerator;
	rhs.numerator = rhs.denominator;
	rhs.denominator = t;
	return operator*(rhs);
}
void Rational::print()
{
	if (numerator%denominator == 0)
		std::cout << numerator / denominator;
	else
		std::cout << numerator << "/" << denominator;
}
int main()
{
	Rational f1(4, 16);
	Rational f2(7, 8);
	Rational res = f1 + f2;
	f1.print();
	std::cout << "+";
	f2.print();
	std::cout << "=";
	res.print();
	std::cout << "\n";

	Rational res1 = f1 - f2;
	f1.print();
	std::cout << "-";
	f2.print();
	std::cout << "=";
	res1.print();
	std::cout << "\n";

	Rational res2 = f1 * f2;
	f1.print();
	std::cout << "*";
	f2.print();
	std::cout << "=";
	res2.print();
	std::cout << "\n";

	Rational res3 = f1 / f2;
	f1.print();
	std::cout << "/";
	f2.print();
	std::cout << "=";
	res3.print();
	std::cout << "\n";
	return 0;
}


你可能感兴趣的:(c++运算符重载(有理数加减乘除))