实验E6:设计一个有理数Rational类(构造和析构函数)

在这里插入图片描述
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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值