I'm having an issue with overloading the << operator. I tried to find an answer already but it seemed that most people just hadn't implemented an override. I'm just learning C++ but I believe it may be a scope issue. I am trying to print out a Rational Number (fractions and integers) class, which has two members for the numerator and denominator.
Header file:
#ifndef RATMATH_H
#define RATMATH_H
using namespace std;
class RatMath
{
public:
RatMath(void);
virtual ~RatMath();
friend ostream& operator<<(ostream &output, RatNum &resultObj);
};
#endif
in the RatMath class:
ostream& operator<<(ostream &output, RatNum &resultNum)
{
int topNum = resultNum.getTopNum();
int botNum = resultNum.getBotNum();
output << topNum << "/" << botNum;
return output;
}
and then to call it from int main(), in a GUI class (which isn't declared in the header-not sure if that is an issue but it was working alright before):
RatNum testObj = RatNum(1, 3);
cout << testObj;
I tried putting the override right in the GUI class to see if it was a scope issue, but then I don't know where to put the 'friend' declaration since the GUI class isn't defined in the header. either way, it didn't work. Any ideas?
Your function has the wrong types:
friend ostream& operator<<(ostream &output, RatNum &resultObj);
should be:
friend ostream& operator<<(ostream &output, **const** RatNum &resultObj);
Your friend declaration of
friend ostream& operator<<(ostream &output, const RatNum &resultObj);
should be placed in the (header of) RatNum class, not in the (header of) RatMath Class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.