(展示封装的好处)重写14.2节中的Rational类,为分子和分母设计新的内部表示形式。定义一个两个元素的整型数组
int r[2];
使用人r[0]做分子,r[1]做分母。Rational类中的函数签名不进行任何改动,因此使用旧Rational类的客户程序无需进行任何修改。仍可适用于新rationa类。
其实上面说了那么多,就一个意思,展示Rational的好处,操作也就一个:替换
下面上代码:
以下代码在VS2019上获得通过!
类头文件代码:
#pragma once
#include <string>
using namespace std;
class Rational
{
public:
Rational();
Rational(int num, int der);
int getNumerator()const;
int getDenominator()const;
void reset(int num, int der);
Rational add(const Rational& secondRational)const;
Rational subtract(const Rational& SecondRational) const;
int CompareTo(const Rational& secondRational)const;
bool operator<(const Rational& SecondRational)const;
string toString()const;
double doubleValue()const;
Rational& operator+=(const Rational& secondRational);
private:
int r[2];
static int gcd(int n, int d);
};
类函数代码:
#include "Rational.h"
#include<cstdlib>
#include<sstream>
Rational::Rational()
{
r[0] = 0;
r[1] = 1;
}
Rational::Rational(int numerator, int denominator)
{
int factor = gcd(numerator, denominator);
r[0] = ((denominator > 0) ? 1 : -1) * numerator / factor;
r[1] = abs(denominator) / factor;
}
int Rational::getNumerator()const
{
return r[0];
}
int Rational::getDenominator() const
{
return r[1];
}
int Rational::gcd(int n, int d)
{
int n1 = abs(n);
int n2 = abs(d);
int gcd = 1;
for (int k = 1; k <= n1 && k <= n2; k++)
{
if (n1 % k == 0 && n2 % k == 0)
{
gcd = k;
}
}
return gcd;
}
Rational Rational::add(const Rational & secondRational)const
{
int n = r[0] * secondRational.getDenominator() +
r[1] * secondRational.getNumerator();
int d = r[1] * secondRational.getDenominator();
return Rational(n, d);
}
Rational Rational::subtract(const Rational & SecondRational) const
{
int n = r[0] * SecondRational.getDenominator()
- r[1] * SecondRational.getNumerator();
int d = r[1]* SecondRational.getDenominator();
return Rational(n, d);
}
int Rational::CompareTo(const Rational & secondRational)const
{
Rational temp = subtract(secondRational);
if (temp.getNumerator() < 0)
return -1;
else if (temp.getNumerator() == 0)
return 0;
else
return 1;
}
bool Rational::operator<(const Rational & SecondRational)const
{
if (CompareTo(SecondRational) < 0)
{
return true;
}
else
return false;
}
string Rational::toString() const
{
stringstream ss;
ss << r[0];
if (r[1] > 1)
ss << "/" << r[1];
return ss.str();
}
double Rational::doubleValue() const
{
return 1.0* getNumerator() / getDenominator();
}
Rational& Rational::operator+=(const Rational & secondRational)
{
*this = add(secondRational);
return*this;
}
由于客户端程序无需改动(也就是主函数代码文档无需改动),所以无需修改遵照原稿。