简体   繁体   English

分数重载运算符+(使用lcm)

[英]Overloading operator + for fractions (using lcm)

I want to compute the sum of two fraction using lcm of numerator and denominator. 我想使用分子和分母的lcm计算两个分数的总和。 That means as a result I want to get a fraction in the reduced form. 这意味着结果是我想得到简化形式的分数。 I have the following cpp file. 我有以下cpp文件。

#include <iostream> //need it for cin and cout
#include "fraction.h"
Fraction::Fraction()
{
   num = 1;
   den = 1;
}

Fraction::Fraction(int n, int d)
{
   int tmp_gcd = gcd(n, d);

   num = n / tmp_gcd;
   den = d / tmp_gcd;
}

int Fraction::gcd(int a, int b)
{
   int tmp_gcd = 1;

// Implement GCD of two numbers;

   return tmp_gcd;
 }

 int Fraction::lcm(int a, int b)
 {
return a * b / gcd(a, b);

 }
 Fraction operator+(const Fraction&a,const Fraction &b)
 {
    int c=(lcm(b.den,a.den)/b.den)*a.num+b.num*(lcm(b.den,a.den)/a.den);
    int d=lcm(b.den,a.den);
    Fraction result(c,d);
    return result;
 }

However this code does not work because lcm is not defined in this scope. 但是,此代码不起作用,因为在此范围内未定义lcm。

What is the key that allows lcm work in this scope? 使lcm在此范围内工作的关键是什么? If you please could explain more, I would be very thankful. 如果您能解释更多,我将非常感谢。

lcm is a member of Fraction . lcmFraction的成员。 You can refer to it just as lcm within members of Fraction ; 您可以在Fraction成员中将其称为lcm but operator+ isn't a member, so you'll have to use the qualified name Fraction::lcm . 但是operator+不是成员,因此您必须使用限定名称Fraction::lcm

It will also need to be static . 它还需要是static (Hopefully it already is, but I can't see the declaration to be sure). (希望它已经是,但是我无法确定该声明)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM