Member Avatar for Search_not

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?

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();

Member Avatar for Search_not

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

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).

Member Avatar for Search_not

Okay, thanks again for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.