Search code examples
c++classoperator-overloadingassignment-operator

No operator "=" matches these operands. I have overloaded it but it doesn't seem to be working properly


I have overloaded the "=" operator to accept objects of my class rational, but it does not seem to be working. Here are my headers and my class definition

#include <iostream>
#include <assert.h>
#include <fstream>
using namespace std;

class rational {
public:

rational();
rational(int numerator, int denominator);
rational(const rational& r);

int numerator() const;
int denominator() const;

const rational& operator = (const rational& rhs);  //this is what I'm having issues with

private:

int myNumerator, myDenominator;

void reduce();
};

Here is my overload implementaion (which I have below main):

const rational& rational::operator = (const rational& rhs) {
if (*this != rhs) { //added asterisk, otherwise operator would not work
    myNumerator = rhs.numerator();
    myDenominator = rhs.denominator();
}
return *this;
}

And below that I am having issues using the "=" operator in the following implementation:

istream& operator>>(istream& is, const rational& r) {
    char divisionSymbol;
    int numerator = 0, denominator = 0;

    is >> numerator >> divisionSymbol >> denominator;
    assert(divisionSymbol == '/');
    assert(denominator != 0);
    rational number(numerator, denominator);
    r = number; /* Error: no operator matches these operands (more specifically no operator found
 which takes a left-hand operand of type 'const rational') but I am unsure how to fix that as the
 assignment operator only takes one parameter (unless I am mistaken)*/
    return is;
}

I cannot for the life of me think of what is not working, possibly a syntax issue? And the professor I have is very old-school so possibly an outdated practice? Any tips would be appreciated.


Solution

  • Problem is not with '=' operator overloading function. Issue is with '>>' operator overloading function. You declared r as const reference parameter and you are trying to modify it by assigning 'number' object to it.

    If you want to modify 'r', you should declare 'r' as just reference as below.

    istream& operator>>(istream& is, rational& r)