I am fairly new in C++ (I have spent all my life in C so I thought it's time to invest some time in learning a new language in order to enrich my knowledge :) ). I have a class named "Rational", I have all its specific functions for getters, setters, constructors, etc.(it's not relevant here). The interesting part is when I try to overload the +,-,,/ operators. I am able to successfully do this between two Rational objects, for example Rational a(1,5),b(5,5),c; c = a + b; so all this works just fine. Now I am trying to upgrade my class by trying to +,-,,/ between a Rational and an integer, for example 2 + a, 10 - b etc. Here is (a snippet of)my code for overloading between Rationals:
Rational.cc
...
Rational Rational::operator+(Rational B) {
int Num;
int Den;
Num = p * B.q + q * B.p;
Den = q * B.q;
Rational C(Num, Den);
C.simplifierFraction();
return C;
}
Rational Rational::operator-(Rational B) {
int Num;
int Den;
Num = p * B.q - q * B.p;
Den = q * B.q;
Rational C(Num, Den);
C.simplifierFraction();
return C;
}
Rational Rational::operator*(Rational B)
{
int Num;
int Den;
Num = p * B.p;
Den = q * B.q;
Rational C(Num, Den);
C.simplifierFraction();
return C;
}
Rational Rational::operator/(Rational B)
{
int Num;
int Den;
Rational invB = inverse(B);
Num = p * invB.p;
Den = q * invB.q;
Rational C(Num, Den);
C.simplifierFraction();
return C;
}
...
Rational.h
Rational operator+(Rational B);
Rational operator-(Rational B);
Rational operator*(Rational B);
Rational operator/(Rational B);
private:
int p;
int q;
protected:
TestRat.cc
int main() {
...
const Rational demi(1,2);
const Rational tiers(1,3);
const Rational quart(1,4);
r0 = demi + tiers - quart;
r1 = 1 + demi;
r2 = 2 - tiers;
r3 = 3 * quart;
r4 = 1 / r0;
...
So when I try to run TestRat.cc it says:
testrat.cc:31: error: no match for ‘operator+’ in ‘1 + r9’
testrat.cc:52: error: passing ‘const Rational’ as ‘this’ argument of ‘Rational Rational::operator+(Rational)’ discards qualifiers
testrat.cc:53: error: no match for ‘operator+’ in ‘1 + demi’
testrat.cc:54: error: no match for ‘operator-’ in ‘2 - tiers’
testrat.cc:55: error: no match for ‘operator*’ in ‘3 * quart’
testrat.cc:56: error: no match for ‘operator/’ in ‘1 / r0’
What must I do in order to be able to make this work? Thanks!