Monday, February 21, 2011

istream operator

int main()
{
    HandPhone A,B;
    A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
    return 0;
}

How should I declare the istream operator to simulate sending sms to another handphone(object)?

From stackoverflow
  • std::istream is a class, not an operator. The << and >> operators can be defined for any two types:

    class A;
    class B;
    
    A operator << (A& a, const B& b)    // a << b;  sends b to a.
    {
       a.sendMessage(b);
       return a;
    }
    
  • This is how to define the >> operator:

    void operator >> (HandPhone& a, HandPhone& b)
    {
        // Add code here.
    }
    

    I have set the return type to void as I am not sure chaining would make sense.

    But it is considered bad design (in the C++ world) to overload operators to do random tasks as it makes the code hard to read. The streaming operators >> and << have a very well defined meaning but sending a message does not look that much like streaming that I would would want to to use the operator this way. I would expect that unmarshalling the object at the destination end of the stream would produce an object very similar to what was placed in at the source end.

    It is a lot easier to do something like this.

    B.sendMessageTo(A,Message("PLOP"));
    

0 comments:

Post a Comment