ukhti
ukhti

Reputation:

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

Upvotes: 0

Views: 662

Answers (2)

Loki Astari
Loki Astari

Reputation: 264571

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

Upvotes: 7

luke
luke

Reputation: 37463

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;
}

Upvotes: 3

Related Questions