当在类名(如 ostream&)后面使用时,& 符号代表什么?运算符 <<(...)?

发布于 2024-08-08 07:45:05 字数 88 浏览 8 评论 0 原文

我知道有关指针的所有信息,而“&”符号的意思是“地址”,但在这种情况下它是什么意思?

另外,重载运算符时,为什么常将参数声明为const?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

╭⌒浅淡时光〆 2024-08-15 07:45:05

在这种情况下,您将返回对 ostream 对象的引用。严格将&符号视为“地址”并不总是适合您。 这里是来自 C++ FAQ Lite 的一些参考信息。

就 const 而言,const 正确性在 C++ 类型安全中非常重要,也是您想要尽可能多做的事情。常见问题解答中的另一个页面在这方面有所帮助。 const 可以帮助您避免与副作用相关的更改在您可能意想不到的情况下弄乱您的数据。

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.

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 page from 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.

回忆凄美了谁 2024-08-15 07:45:05

根据 & 符号的上下文,它可能表示两种不同的含义。您的具体问题的答案是,它是一个参考,而不是“地址”。它们是非常不同的东西。了解其中的差异非常重要。

C++ 参考

将参数设置为 const 的原因是为了确保它们不会被更改的功能。这保证了函数的调用者传入的参数不会被更改。

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.

C++ Reference

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.

魄砕の薆 2024-08-15 07:45:05

这意味着该变量是一个引用。它有点像指针,但又不是。

请参阅:参考 (C++)

It means that the variable is a reference. It's kind of like a pointer, but not really.

See: Reference (C++)

春花秋月 2024-08-15 07:45:05

在 C++ 类型声明中,& 符号表示“引用”。在这种情况下,运算符<<返回对ostream对象的引用。

由于它实际上返回 *this 它实际上是相同的 ostream 对象,并且意味着您可以链接调用 operator <<,类似于此:

os << "Hello" << " " << "World" << endl;

In C++ type declarations, the ampersand means "reference". In this case operator << returns a reference to an ostream object.

Since it actually returns *this it's actually the same ostream object, and means you can chain calls to operator <<, similar to this:

os << "Hello" << " " << "World" << endl;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文