C++ Operator Overload << ostream operator

Description

C++ Operator Overload << ostream operator

 
#include <iostream>
#include <string>
#include <fstream>
#include <map>
 
using namespace std;
 
class MyClass/*from  w ww.  j a v  a  2  s .  c  o m*/
{
    friend ostream &operator <<(ostream &out, MyClass &oven);
public:
    typedef map<ostream *, bool> FlagMap;
    int i1;
    int i2;
    int i3;
    string name;
    static FlagMap Flags;
};
 
MyClass::FlagMap MyClass::Flags;
ostream &operator <<(ostream &out, MyClass &oven)
{
    bool full = true;
    MyClass::FlagMap::iterator iter =
        MyClass::Flags.find(&out);
    if (iter != MyClass::Flags.end())
    {
        full = iter->second;
    }
 
    if (full)
    {
        out << "High Voltage Radiation: ";
        out << oven.i1 << endl;
        out << "Radioactive Food Count: ";
        out << oven.i2 << endl;
        out << "Leak Level: ";
        out << oven.i3 << endl;
        out << "Oven Name: ";
        out << oven.name;
    }
    else
    {
        out << oven.i1 << ",";
        out << oven.i2 << ",";
        out << oven.i3 << ",";
        out << oven.name;
    }
 
    return out;
}
 
istream &operator >(istream &in, MyClass &oven)
{
    in >> oven.i1;
    in >> oven.i2;
    in >> oven.i3;
    in >> oven.name;
    return in;
}
 
struct FullOvenManip {};
 
void FullOvenInfo(FullOvenManip x) {}
typedef void(*FullPtr)(FullOvenManip);
 
ostream &operator << (ostream &out, FullPtr)
{
    MyClass::Flags[&out] = true;
    return out;
}
 
struct MinOvenManip {};
 
void MinOvenInfo(MinOvenManip x) {}
typedef void(*MinPtr)(MinOvenManip);
 
ostream &operator << (ostream &out, MinPtr)
{
    MyClass::Flags[&out] = false;
    return out;
}
 
int main()
{
    MyClass myoven;
    myoven.i1 = 9832;
    myoven.i2 = 7624;
    myoven.i3 = 3793;
    myoven.name = "Burnmaster";
 
    cout << myoven << endl;
    cout << FullOvenInfo << myoven << endl;
    cout << MinOvenInfo << myoven << endl;
 
    return 0;
}



PreviousNext

Related