分数类的乘数运算符的重载

时间:2017-03-21 19:55:46

标签: c++ class

你能解释一下如何正确地将分数乘以数字吗?试图重载,但我得到编译器错误:

  

二元运算符*:运算符接受类型的左操作数   找不到SimpleFraction

class SimpleFraction 
{
static int findGcd(int a, int b)
{
    while (a&&b)
    {
        if (a > b)
            a %= b;
        else
            b %= a;

    }
    return (a == 0) ? b : a;
}

private:
int a,
    b;
public:
SimpleFraction(int a1 = 0, int a2 = 1) :a(a1), b(a2) 
{
    if (a2 == 0)
        throw std::runtime_error("zero division error");
}

friend ostream& operator<<(ostream&out, const SimpleFraction& f)
{
    return out << f.a << "/" << f.b ;
}

friend istream& operator >> (istream&in, SimpleFraction& f) 
{
    char t;
    return in >> f.a >>t>> f.b;
}

friend SimpleFraction operator *(const SimpleFraction&x, int n) 
{
    int a = x.a *n;
    int gcd = finGcd(a, x.b);
    return SimpleFraction(a / gcd, x.b / gcd);
}
};

当我输入此类代码时,我收到了错误消息

int main()
{
SimpleFraction SFArray1(2, 2);
SimpleFraction r = SFArray1 * 2;
cout << r;
return 0;
}

1 个答案:

答案 0 :(得分:0)

friend SimpleFraction operator *(const SimpleFraction&x, int n)

您无需在此处使用friend关键字。作为课程的一部分,操作员*应该被重载。您的函数签名应如下所示:

SimpleFraction operator *(const SimpleFraction& rightOperand) const {
/* ...implementation which should use values of "this" and rightOperand and return a newly instantiated SimpleFraction*/
    SimpleFraction result(this->a * rightOperand.a, this->b * rightOperand.b);
    return result;
}
OP编辑后

更新

查看main中的代码,你必须使用int值进行另一次重载:

SimpleFraction operator *(const int& rightOperand) const {
    SimpleFraction result(this->a * rightOperand.a, this->b); // I'm guessing you take "a" as a numerator  
    return result;
}

此外,在main()功能中,您使用SimpleFraction =运算符。因此,您应该按照Rule of Three实施operator=功能以及复制构造函数