C ++:将对象添加到当前对象

时间:2014-03-05 20:26:07

标签: c++ binary-operators

我正在尝试创建一个成员函数,它将一个对象Fraction f添加到当前对象并返回对当前对象的引用。我的第二个函数是一个非朋友帮助操作符,它添加了两个Fraction对象并返回结果的副本。我不确定如何去做这件事并且正在寻找一些建议。几乎所有对象都只是先前在成员函数中简化的分数。基本上我所做的只是添加简化的分数。这是我到目前为止所做的:

//header.h       
class Fraction {
        int num;
        int den;
    public:
        Fraction();
        Fraction(int, int);
        Fraction& operator+=(const Fraction& f);
        friend bool operator==(const Fraction&, const Fraction&);
        void simplify();
        void display() const;
    };

    Fraction operator+(const Fraction&, const Fraction&);

和模块:

//module.cpp

    #include "Fraction.h"
    #include <iostream>


    Fraction::Fraction() {
        num = 0;
        den = 0;
    }

    Fraction::Fraction(int n, int d) {
        num = n;
        den = d;
        simplify();
    }

    void Fraction::simplify() {
        int temp = den;
        int a = num;
        int b = den;
        int gcd;
        if (b > a) {
            b = num;
            a = den;
        }
        while (temp != 0) {
            temp = a % b;
            a = b;
            b = temp;
        }
        gcd = a;
        num /= gcd;
        den /= gcd;
    }

    void Fraction::display() const {
        std::cout << num << "/" << den << std::endl;
    }

    //member function in question
    Fraction& Fraction::operator+=(const Fraction& f) {
        num += f.num;
        den += f.den;
        return *this;
    }

//member function in question
        Fraction operator+(const Fraction&, const Fraction&) {

    }
编辑:猜测我以前没那么明确,部分原因是辅助功能未被泄露。我尝试定义成员函数,上面的代码是我目前所拥有的。我不确定它是否合乎逻辑,因为我仍在通过其他定义。非朋友助手操作员是我难倒的,不知道该怎么做。如果我可以得到一些关于我对+ =成员运算符的定义是否正确以及如何处理非朋友助手操作符的建议的帮助,那将是很好的。抱歉有任何困惑。

1 个答案:

答案 0 :(得分:0)

因为你已经简化了分数,所以你要做的就是使用这个等式:
summing two fractions

,代码如下:

 Fraction& Fraction::operator+=(const Fraction& f) {
        num = num * f.den + f.num * den;
        den *= f.den;
        simplify();
        return * this;
    }

修改 有关运算符重载的更多信息,请查看this question