nikhil
nikhil

Reputation: 9385

Invalid conversion error when overloading ostream& operator<<

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.

Upvotes: 0

Views: 1350

Answers (2)

John Yang
John Yang

Reputation: 1360

Although I am not sure why you get such error message, I do found an error: you should add:

return os;

in your friend function.

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 792497

Your first issue is that you try to forward declare ostream as a class. Assuming that you mean to use std::ostream, you can't do that, its not legal.

For one, it's a typedef for 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 for ostream so when you try to << a string literal, the compiler trys to convert the string literal to a Rational type as that is the only type that has a << overload visible.

Simply, you need to #include <ostream> and qualify ostream with std:: where you use it.

A third point is that your overload of operator<< needs to return something. You should either append a return os; statement or simply return the whole streaming expression.

Upvotes: 4

Related Questions