【发布时间】: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 << cout << endl”,而是教授测试你对运算符和运算符重载的理解。 -
ostream& operator<<(ostream& o, T& t)应该是ostream& operator<<(ostream& o, const T& t)
标签: c++ operator-overloading ostream