C++ 在 ostream& 运算符 <<(...) 之类的类名之后使用时,与号是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1572016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the ampersand for when used after class name like ostream& operator <<(...)?
提问by Omar
I know about all about pointers and the ampersand means "address of" but what's it mean in this situation?
我知道关于指针的所有信息,并且与号的意思是“地址”,但在这种情况下它是什么意思?
Also, when overloading operators, why is it common declare the parameters with const?
另外,在重载运算符时,为什么通常用 const 声明参数?
采纳答案by Kyle Walsh
In that case you are returning a reference to an ostream object. Strictly thinking of ampersand as "address of" will not always work for you. Here's some info from C++ FAQ Lite on references.
在这种情况下,您将返回对 ostream 对象的引用。严格地将&符号视为“地址”并不总是适合您。以下是 C++ FAQ Lite 关于参考资料的一些信息。
As far as const goes, const correctness is very important in C++ type safety and something you'll want to do as much as you can. Another pagefrom the FAQ helps in that regard. const helps you from side effect-related changes mucking up your data in situations where you might not expect it.
就 const 而言,const 正确性在 C++ 类型安全中非常重要,并且您会尽可能多地做一些事情。常见问题解答中的另一页在这方面有所帮助。const 帮助您避免与副作用相关的更改在您可能不期望的情况下破坏您的数据。
回答by nathan
Depending on the context of the ampersand it can mean 2 different things. The answer to your specific question is that it's a reference, not "the address of". They are very different things. It's very important to understand the difference.
根据&符号的上下文,它可以表示两种不同的含义。你的具体问题的答案是它是一个参考,而不是“地址”。它们是非常不同的东西。了解差异非常重要。
The reason to make parameters const is to ensure that they are not changed by the function. This guarantees the caller of the function that the parameters they pass in will not be changed.
将参数设为 const 的原因是为了确保它们不会被函数更改。这保证了函数的调用者他们传入的参数不会被改变。
回答by Roger Lipscombe
In C++ type declarations, the ampersand means "reference". In this case operator <<
returns a reference to an ostream
object.
在 C++ 类型声明中,与号表示“引用”。在这种情况下,operator <<
返回对ostream
对象的引用。
Since it actually returns *this
it's actually the same ostream
object, and means you can chain calls to operator <<
, similar to this:
由于它实际上返回*this
它实际上是同一个ostream
对象,这意味着您可以将调用链接到operator <<
,类似于:
os << "Hello" << " " << "World" << endl;
回答by Jesper
It means that the variable is a reference. It's kind of like a pointer, but not really.
这意味着该变量是一个引用。它有点像一个指针,但不是真的。
See: Reference (C++)
请参阅:参考(C++)