-1

Error message:

class.cpp: In function 'RationalNumber operator++(const RationalNumber&, int)':
class.cpp:27:28: error: assignment of member 'RationalNumber::numerator' in read-only object
  r.numerator = r.numerator+1;

Why is it "in read-only object"?

class.h file

#ifndef CLASS_H
#define CLASS_H
#include <iostream>
using namespace std;
// #include "class2.h"

class RationalNumber
{
 private:
  int numerator,denominator;
 public:
    RationalNumber(int x,int y);
    RationalNumber();
    friend ostream& operator << (ostream& os,const RationalNumber& x);
    friend RationalNumber operator++ (const RationalNumber& r, int dummy);
    RationalNumber operator- (const RationalNumber& r) {
        RationalNumber r3;
        //cout << numerator << " " << r.numerator<<endl;
        r3.numerator = (numerator * r.denominator)-(r.numerator * denominator);
        r3.denominator = r.denominator * denominator;
        return r3;
    }

};
#endif

main.cpp

#include <iostream>
using namespace std;
#include "class.h"
// #include "class2.h"

int main()
{
    RationalNumber r1(21,7),r2(67,31),r3;
    r3 = r1 - r2;
    cout << r3;
    r1++;
    cout << r1;
}

cpp part with the error

RationalNumber operator++ (const RationalNumber& r, int dummy) 
{
    RationalNumber temp;
    temp = r;
    r.numerator = r.numerator+1;
    return temp;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
jaxk
  • 7
  • 3
  • 4
    `r` is const. You can't change it. – tkausl Mar 25 '20 at 19:39
  • I second that it is confusing, if I see `RationalNumber r; ... r++;` i expcept it to increment by `1`. How about incrementing a `RationalNumber x(3,6);` will `++` increment by `1/6` or `1/2` because `3/6 == 1/2` ? – 463035818_is_not_an_ai Mar 25 '20 at 19:58

1 Answers1

-1

As pointed out, the const operator indicates you cannot modify r. Here is a correct declaration and implementation of your postfix ++ operator:

...
    friend RationalNumber& operator++ (RationalNumber& r, int dummy);
...
RationalNumber& operator++ (RationalNumber& r, int dummy) 
{
    r.numerator += 1;
    return r;
}

However, also as pointed out, it is confusing to use the increment operator like this. It would seem to make more sense if it increased the fraction by 1 whole and not the numerator by 1. Like 3/7 + 1 = 10/7
Instead, you're doing 3/7 + 1/7 = 4/7

Note: I've removed the temp variable so that you return the original object because that is what the operator is meant to do, not create a new object.

amr ras
  • 136
  • 10