0

我编写了以下用于修改 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

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

4

1 回答 1

5

假设您有一个将两个ints 作为参数的构造函数(如果不这样做,则应该这样做,而不仅仅是为了我的回答),请执行以下操作:

return Fraction(-numerator, denominator);
于 2013-10-23T23:09:50.347 回答