简体   繁体   English

C++ 直接从 operator< 返回

[英]C++ return directly from operator<<

Is it allowed to directly return while we are sending to ostream ?发送到ostream时是否允许直接返回?

For example, instead of writing:例如,而不是写:

ostream& operator<<(ostream& os, Foo foo) {
    os << foo.a << foo.b;
    return os;
}

Instead, can I directly write:相反,我可以直接写:

ostream& operator<<(ostream& os, Foo foo) {
    return os << foo.a << foo.b;
}

I tried it, and it seems to work but I don't know if it's the right thing to do.我试过了,它似乎有效,但我不知道这样做是否正确。 Is there any problem with doing the second version?做第二个版本有问题吗?

The two code snippets you post are entirely equivalent.您发布的两个代码片段完全相同

Why?为什么? Because (I'm assuming here, for the sake of argument, that foo.a and foo.b are simple data types like int ) the << operator for std::ostream returns a reference to itself (see the "Return Value" section in the linked document).因为(我在这里假设,为了论证, foo.afoo.b是像int这样的简单数据类型) std::ostream<<运算符返回对自身引用(请参阅“返回值”链接文档中的部分)。

Thus, in your first code snippet, the return os;因此,在您的第一个代码片段中, return os; line returns a reference to the os object referenced by the first argument. line 返回对第一个参数引用的os对象的引用。 In your second snippet, the two << operations each evaluate as a reference to that same object ... so you are returning a reference to the exact same object.在您的第二个代码段中,两个<<操作各自评估为对同一对象的引用......因此您将返回对完全相同对象的引用。

To make the second version a bit clearer, you may like to enclose the returned expression in parentheses:为了使第二个版本更清晰一些,您可能希望将返回的表达式括在括号中:

ostream& operator<<(ostream& os, Foo foo) {
    return (os << foo.a << foo.b);
}

Is it allowed to directly return while we are sending to ostream?我们发送到ostream时是否允许直接返回?

Yes, it is allowed.是的,这是允许的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM