I am a beginner to OOPS concept. I am working on Operator overloading now. I run into the error no match for operator<<
when I use an overloaded increment operator inside cout
. It works fine when I remove the overloaded increment from cout. Logically, I don't feel like anything wrong with the code. Still, I do not know why I get the error? Below is my code for better understanding of the issue.
#include <iostream>
using namespace std;
class Digit
{
private:
int digit;
public:
Digit(int n)
{
digit = n;
}
Digit& operator++();
Digit operator++(int); //overloaded postfix increment. Dummy argument used
Digit& operator--();
Digit operator--(int); //overloaded postfix decrement. Dummy argument used
friend ostream& operator<<(ostream& out, Digit& x); //overloaded << prototype
int GetDigit()
{
return digit;
}
};
Digit Digit::operator++(int)
{
//Create a temporary object with a variable
Digit temp(digit);
//Use prefix operator to increment this Digit
++(*this);
return temp; //return temporary result
}
Digit& Digit::operator++()
{
if (digit==9)
digit = 0;
else
++digit;
return *this;
}
Digit Digit::operator--(int)
{
//Create a temporary object with a variable
Digit temp(digit);
//Use prefix operator to increment this Digit
--(*this);
return temp; //return temporary result
}
Digit& Digit::operator--()
{
if (digit==0)
digit = 9;
else
--digit;
return *this;
}
int main()
{
using namespace std;
Digit n(9);
Digit x(0);
cout << n++ << endl;
cout << x-- << endl;
return 0;
}
ostream& operator<<(ostream& out, Digit& x)
{
out << x.digit;
return out;
}
The lines cout << n++ << endl; cout << x-- << endl;
inside main()
causes the error.