declare.h
#pragma once
#include <string>
using namespace std;
class Rational;
int gcd(int a, int b);
void find_true(int& a, int& b);
int find_cnt();
function.h
#ifndef MAIN_CPP_HEAD_H
#define MAIN_CPP_HEAD_H
#include "declare.h"
extern int objCount;
int gcd(int a, int b) {//最大公约数
return b == 0 ? a : gcd(b, a % b);
}
void find_true(int& a, int& b) {//化简为真分数
int t = gcd(a, b);
a /= t;
b /= t;
}
#endif //MAIN_CPP_HEAD_H
Rational.h
#include <iostream>
#include "declare.h"
using namespace std;
#ifndef E6_RATIONAL_H
#define E6_RATIONAL_H
extern int objCount;
class Rational {
int nume, deno;//分子 分母
public:
Rational(int nume, int deno) :nume(nume), deno(deno) {//create
if (nume * deno < 0) {
this->nume = -abs(nume);//统一将负数的规定为分子为负,分母为正
this->deno = abs(deno);
}
objCount++;
}
~Rational() {
objCount--;
}
Rational(const Rational& r) {
cout << "calling copy function" << endl;
nume = r.nume;
deno = r.deno;
}
static void show_objCount() {//必须写成static,否则无法当objCount==0时候无法查看
cout << "ths number of Rational is" <<" "<<objCount<<endl;
}
Rational operator + (const Rational r) {
int t = gcd(deno, r.deno);
int a = (nume * r.deno + r.nume * deno) / t;
int b = deno * r.deno / t;
//以下是化简成真分数
find_true(a, b);
return Rational(a, b);
}
Rational operator - (const Rational r) {
return *this + Rational(-r.nume, r.deno);
}
Rational operator * (Rational& r) const {
int a = nume * r.nume;
int b = deno * r.deno;
find_true(a, b);
return Rational(a, b);
}
Rational operator / (Rational& r) const {
int a = nume * r.deno;
int b = deno * r.nume;
find_true(a, b);
return Rational(a, b);
}
void show() const {
cout << "The answer is " << nume << "/" << deno << endl;
}
friend ostream& operator <<(ostream& os, Rational r);
};
ostream& operator <<(ostream& os, Rational r) {//不写成引用是因为在这个实验里
//cout时候基本都是右值,如果之后实验需要用左值,就需要写成引用了
return os << r.nume << "/" << r.deno;
}
#endif //E6_RATIONAL_H
main.h
#include <iostream>
#include "Rational.h"
#include "function.h"
#include <string>
using namespace std;
int objCount = 0;
int main() {
//当系统中一个class也没有时候
Rational::show_objCount();
Rational a(6, 5);
Rational b(9, 6);
//当有两个的时候
Rational::show_objCount();
cout << a + b;
cout << a - b;
cout << a * b<<endl;
cout << a / b << endl;
return 0;
}