小甲鱼-C++快速入门笔记 26 之运算符重载2

重点要掌握的:

1、欧几里得算法

2、运算符重载

#include <iostream>
#include <string>
#include <cmath>
 
using namespace std;
 
class Rational
{
public:
	Rational(int num, int denom);  //num=分子,denom=分母
 
	Rational operator+(Rational rhs); //rhs = right hand side
	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();
}
 
// normalize() 对分数进行简化操作包括:
// 1.只允许分子为负数,如果分母为负数则把负数挪到分子部分,1/-2 == -1/2
// 2.利用欧几里得算法(辗转求余原理)将分数进行简化:2/10=>1/5
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*d + b*c;
	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)
		cout << numerator / denominator;
	else
		cout << numerator << "/" << denominator;
	
}
 
int main()
{
	Rational f1(2, 16);
	Rational f2(7, 8);
 
	// 测试有理数的加法运算
	Rational res = f1 + f2;
	f1.print();
	cout << " + ";
	f2.print();
	cout << " = ";
	res.print();
	cout << endl;
 
	// 测试有理数的减法运算
	Rational sub = f1 - f2;
	f1.print();
	cout << " - ";
	f2.print();
	cout << " = ";
	sub.print();
	cout << endl;
 
	// 测试有理数的乘法运算
	Rational mul = f1 * f2;
	f1.print();
	cout << " * ";
	f2.print();
	cout << " = ";
	mul.print();
	cout << endl;
 
	// 测试有理数的加法运算
	Rational div = f1 / f2;
	f1.print();
	cout << " / ";
	f2.print();
	cout << " = ";
	div.print();
	cout << endl;
 
	return 0;
}

一些小TIPS:

1、千万不要仅仅因为“我懂得这么做”而去重载一个操作符,应该只有在必要的时候,比如实现一种新的数据类型时,才重载操作符;

2、重载操作符的目的是为了让代码更容易阅读和理解;

3、注意在重载操作符时,千万不要让它们失去原始的意义,你完全重载+然后对它进行减法操作,但这绝不是创意的表现。

上一篇:UVM 基础入门(一)


下一篇:Oracle-数据伪列ROWNUM, ROWID