istream operator

istream operator

本文关键字:operator istream      更新时间:2023-10-16
int main()
{
    HandPhone A,B;
    A>>B;//overloading operator>> to simulate sending sms to another handphone(object)
    return 0;
}

我应该如何声明istream运算符来模拟向另一个手机(对象(发送短信?

这是定义>>运算符的方法:

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

我已将返回类型设置为 void,因为我不确定链接是否有意义。

但是(在C++世界中(使操作员过载以执行随机任务被认为是糟糕的设计,因为它会使代码难以阅读。流式处理运算符>>和<<具有非常明确定义的含义,但发送消息看起来不太像我希望以这种方式使用运算符的流式传输。我希望在流的目标端解组对象将生成一个与源端放置的对象非常相似的对象。

做这样的事情要容易得多。

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

std::istream 是一个类,而不是一个运算符。 可以为任意两种类型定义<<运算符和>>运算符:

class A;
class B;
A operator << (A& a, const B& b)    // a << b;  sends b to a.
{
   a.sendMessage(b);
   return a;
}