【问题标题】:Is it possible to cout object in C++ like this obj << cout << endl是否可以像这样在 C++ 中计算对象 obj << cout << endl
【发布时间】:2019-06-05 18:22:19
【问题描述】:

我们有一堂课,教授要求我们重载 ostream 以这种方式打印对象(说我们有对象 t

cout << t << endl;

然后我们被要求以这种方式计算同一个对象

t << cout << endl;

这是如何工作的,为什么?

ostream& operator<<(ostream& o, T& t)
{
   return o << t.member;
}

// This is usual way and "normal" that I know about but won't work on both ways

预期的输出是相同的,但第二种方式令人困惑。为什么有人要使用它?

【问题讨论】:

  • 我不清楚您想要回答哪些问题。
  • 教授并不是说,“你应该总是写t &lt;&lt; cout &lt;&lt; endl”,而是教授测试你对运算符和运算符重载的理解。
  • ostream&amp; operator&lt;&lt;(ostream&amp; o, T&amp; t) 应该是ostream&amp; operator&lt;&lt;(ostream&amp; o, const T&amp; t)

标签: c++ operator-overloading ostream


【解决方案1】:

正如任何good book 或教程应该告诉您的那样,对于任何运算符X,表达式a X b 将(如果找到合适的重载)等于operatorX(a, b)

或者如果a(在a X b中)将运算符重载为成员函数,则它等于a.operatorX(b)

如果我们现在采用cout &lt;&lt; t,则将调用operator&lt;&lt;(cout, t)cout.operator&lt;&lt;(t),具体取决于t 的类型。

应该很容易猜到,将顺序颠倒到t &lt;&lt; cout 将是operator&lt;&lt;(t, cout)t.operator&lt;&lt;(cout)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-06
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多