c++ - Overloading operator + for fractions (using lcm) -
i want compute sum of 2 fraction using lcm of numerator , denominator. means result want fraction in reduced form. have following cpp file.
#include <iostream> //need cin , 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 2 numbers; return tmp_gcd; } int fraction::lcm(int a, int b) { return * 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 code not work because lcm not defined in scope.
what key allows lcm work in scope? if please explain more, thankful.
lcm member of fraction. can refer lcm within members of fraction; operator+ isn't member, you'll have use qualified name fraction::lcm.
it need static. (hopefully is, can't see declaration sure).
Comments
Post a Comment