Here is the prototype of my class Rational
#ifndef RATIONAL_H
#define RATIONAL_H
//forward declaration
class ostream;
class Rational
{
int numerator,denominator;
public:
// the various constructors
Rational();
Rational(int);
Rational(int,int);
//member functions
int get_numerator()const{return numerator;}
int get_denominator()const{return denominator;}
// overloaded operators
// relational operators
bool operator==(const Rational&)const;
bool operator<(const Rational&)const;
bool operator<=(const Rational&)const;
bool operator>(const Rational&)const;
bool operator>=(const Rational&)const;
//arithmetic operators
Rational operator+(const Rational&)const;
Rational operator-(const Rational&)const;
Rational operator*(const Rational&)const;
Rational operator/(const Rational&)const;
//output operator
friend ostream& operator<<(ostream&, const Rational&);
};
#endif //RATIONAL_H
And this is the implementation of the overloaded output operator<< in rational.cpp
// friend output operator
ostream& operator<<(ostream& os, const Rational& r)
{
os<<r.get_numerator()<<"/"<<r.get_denominator();
}
When I try to compile I get the following error
g++ -c rational.cpp
rational.cpp: In function ‘ostream& operator<<(ostream&, const Rational&)’:
rational.cpp:81:26: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
rational.cpp:7:1: error: initializing argument 1 of ‘Rational::Rational(int)’ [-fpermissive]
I wanted to be able to display the rational number as numerator/denominator when it is passed to the << operator.
Your first issue is that you try to forward declare
ostreamas a class. Assuming that you mean to usestd::ostream, you can’t do that, its not legal.For one, it’s a
typedeffor a template specialization, not a class itself.Second, because you don’t
#include <ostream>you don’t have a definition for any of the standard<<overloads forostreamso when you try to<<a string literal, the compiler trys to convert the string literal to aRationaltype as that is the only type that has a<<overload visible.Simply, you need to
#include <ostream>and qualifyostreamwithstd::where you use it.A third point is that your overload of
operator<<needs to return something. You should either append areturn os;statement or simplyreturnthe whole streaming expression.