0

How do I overload the cout and cin operators so as to get input and show output using an object?

Heres a simple example of what I'm trying to do:

class Temp{
    double fTemp;

    public:
        double FahrToCelsius(double fTemp){
            return (fTemp - 32.0) / 1.8;
        }

        friend std::ostream operator<<(std::ostream Out, const Temp& tempVar);  //overloading of the ostream "cout"

        friend std::istream& operator>>(std::istream& In, Temp& tempVar);   //overloading of the istream "cin"   
}

//using namespace std
int main(void){
    Temp tempVar;   //create object

    cout << "Enter fahrenheit temp: " << endl;
    cin >> tempVar;

    cout << "Fahrenheit Temp: " << tempVar.FahrToCelsius(tempVar);

  return 0;
}

Am I doing it wrong or is there a way to overload the operators?

2
Contributors
4
Replies
18
Views
3 Years
Discussion Span
Last Post by Search_not
1

I think this might be what you're trying to do. Note that in your code, you wrote declarations for the overloaded operators, but you didn't actually write any code for them.

#include <iostream>

using namespace std;

class Temp{
  double fTemp;
    public:

        double FahrToCelsius(){
            return (fTemp - 32.0) / 1.8;
        }
        friend std::ostream operator<<(std::ostream Out, const Temp& tempVar);  //overloading of the ostream "cout"
        friend std::istream& operator>>(std::istream& In, Temp& tempVar);   //overloading of the istream "cin"   
};


istream& operator>> ( istream& is, Temp& obj )
{
   is >> obj.fTemp;
   return is;
}

ostream& operator<< ( ostream& os, Temp& obj )
{
   os << obj.FahrToCelsius();
   return os;
}


int main(){
    Temp tempVar;   //create object
    cout << "Enter fahrenheit temp: " << endl;
    cin >> tempVar;
    cout << "Fahrenheit Temp: " << tempVar;
  return 0;
}

Note that when this code applies an object of type Temp to the overloaded << operator, what's actually happening is a call to the object's FahrToCelsius function. If this is what you wanted, that's great; it's a bit overkill for this actual case, and also counter-intuitive. If you really wanted to do this, I wouldn't bother with the overloading of the << operator and I wuold simply call the object's function myself:

cout << obj.FahrToCelsius();

Edited by Moschops

0

Thanks a lot! Would it be possible to do the same thing with enum types as well? excluding the object of course

0

It's possible to do it with anything you like. If you did it with an enum type, you'd presumably be taking in a string or an int, and you'd need to write the code to interpret that string or int and set the appropriate enum value in your class (or just plain enum).

Edited by Moschops

0

Okay, thanks again for the help!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.