否定分数但不修改原始分数

时间:2013-10-23 23:05:30

标签: c++

我编写了以下用于修改Fraction对象的类。

#include "Fraction.h"
#include "GCD.h"
#include <iostream>
using std::cout;

//Implementation of the timesEq() member function
//Performs similar operation as the *= operator on the built-in types
const Fraction & Fraction::timesEq(const Fraction & op )
{
    numerator *= op.numerator;
    denominator *= op.denominator;

    simplify();  // will make sure that denominator is positive and
                 //   will invoke gcd() function to reduce fraction
                 //   as much as possible

    return (*this); // returns the object which invoked the method
}

const Fraction & Fraction::plusEq (const Fraction & op )
{
    numerator *= op.denominator;
    numerator += op.numerator * denominator;
    denominator *= op.denominator;

    simplify();  // will make sure that denominator is positive and
                 //   will invoke gcd() function to reduce fraction
                 //   as much as possible

    return (*this); // returns the object which invoked the method
}

const Fraction & Fraction::minusEq (const Fraction & op )
{
    numerator *= op.denominator;
    denominator = denominator * op.denominator;
    numerator -= op.numerator;

    simplify();  // will make sure that denominator is positive and
                 //   will invoke gcd() function to reduce fraction
                 //   as much as possible

    return (*this); // returns the object which invoked the method
}

const Fraction & Fraction::divideEq (const Fraction & op )
{
    numerator *= op.denominator;
    denominator *= op.numerator;

    simplify();  // will make sure that denominator is positive and
                 //   will invoke gcd() function to reduce fraction
                 //   as much as possible

    return (*this); // returns the object which invoked the method
}

Fraction Fraction::negate(void) const
{
    return (*this * -1);
}

void Fraction::display(void)const {
    cout << numerator << "/" << denominator;
}

void Fraction::simplify(void)
{
    gcd = gcd(numerator, denominator);
    numerator /= gcd;
    denominator /= gcd;
}

但我遇到了negate功能的问题。 我正在使用这样的函数:B = A.negate(),因此,我无法修改原始A对象,但需要将否定对象分配给B

现在我的实施是一个错误:
Error: no operator "*" matches these operands
operand types are: const Fraction * int

我不确定我做错了什么。需要改变什么?

1 个答案:

答案 0 :(得分:5)

假设你有一个构造函数需要两个int作为参数(如果你不是,你应该,而不仅仅是为了我的答案),这样做:

return Fraction(-numerator, denominator);