gpt4 book ai didi

c++ - 级联流插入运算符不起作用

转载 作者:行者123 更新时间:2023-11-30 03:36:47 25 4
gpt4 key购买 nike

我正在阅读一篇关于 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
}

最佳答案

这是 UB,因为应该返回对象的函数在没有 return 语句的情况下结束。它可能会很好地工作,但不能保证。

来自标准,$6.6.3/2 The return statement[stmt.return] :

(强调我的)

Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main (basic.start.main) results in undefined behavior.


您可能想查看 clang 的结果;给出警告

warning: control reaches end of non-void function [-Wreturn-type]

并导致无限递归。

关于c++ - 级联流插入运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com