我正在閱讀有關Overloading the Stream Insertion Operator (<<)的文章。它強調應該返回輸出流對象以確保操作員級聯正確。但似乎沒有回報,輸出仍然是正確的,這裏有什麼問題?級聯流式插入操作符不起作用
#include<iostream>
class Rational
{
friend std::ostream& operator<<(std::ostream&, const Rational&);
private:
int numerator;
int denominator;
public:
Rational(int num, int den): numerator{num}, denominator{den} {}
};
std::ostream& operator<<(std::ostream& lhs, const Rational& rhs)
{
lhs << rhs.numerator << "/" << rhs.denominator;
//return lhs;
}
int main()
{
Rational r1(3, 5);
std::cout << "The value of r1 is " << r1 << std::endl; // After commenting return lhs; still works fine
}