-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
  • 505,946
  • 29
  • 409
  • 696
jaxk
  • 7
  • 3

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
  • 131
  • 9