运算符重载

发布于 2024-09-28 06:57:52 字数 252 浏览 3 评论 0原文

iarray<T>& operator =    (iarray<T>& v)

为什么返回类型是 iarray& 而不是 iarray

更新

有人可以详细说明为什么iarray常量 &v

iarray<T>& operator =    (iarray<T>& v)

Why the return type is iarray<T>& not iarray<T> ?

UPDATE

Can someone elaborate in great detail why iarray<T> const &v ?

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

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

发布评论

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

评论(3

九厘米的零° 2024-10-05 06:57:52

因为您不想仅仅为了链接而返回数组的副本。返回引用是一个更好的选择,因为它不会导致构造副本。

Because you don't want to return a copy of the array just for the sake of chaining. Returning a reference is a better option as it doesn't result in a copy being constructed.

耳根太软 2024-10-05 06:57:52

因为这样你就可以有效地链接它们,例如。

a = b = c;

请参阅C++ 常见问题解答

Because then you can chain them efficiently, eg.

a = b = c;

See the C++ FAQ.

惯饮孤独 2024-10-05 06:57:52

为什么返回类型是iarray&不是 iarray 吗?

因为分配的结果是对刚刚分配的内容的引用。例如,a = b 的结果应该是对 a 的引用,因此您可以像 c = a = b; 中那样将它们链接在一起这实际上是 a = b; c = a;。 (是的,人们在极少数情况下喜欢这样做;不,我不知道为什么将其分成两行如此困难。)因此您的代码应该如下所示:

iarray<T>& iarray<T>::operator = (const iarray<T>& v)
{
   // ... copy `v`'s state over this object's ...

   return *this;
}

有人可以详细说明为什么 iarray const &v 吗?

因为赋值操作没有必要改变右侧;这是意想不到的行为。如果您的对象中有一些奇怪的东西需要更改,例如引用计数,那么您应该更喜欢声明该部分 mutable 而不是不允许 const 右侧表达式。您可以为 const 参数传递一个非 const 值,但反之则不然。

Why the return type is iarray& not iarray ?

Because the result of an assignment is a reference to what just got assigned. For example, the result of a = b should be a reference to a so you can chain them together like in c = a = b; which is effectively a = b; c = a;. (Yes, people like doing this on rare occasions; no, I don't know why it's such a hardship to break it into two lines.) Thus your code should look like:

iarray<T>& iarray<T>::operator = (const iarray<T>& v)
{
   // ... copy `v`'s state over this object's ...

   return *this;
}

Can someone elaborate in great detail why iarray const &v ?

Because an assignment operation has no business changing the right-hand side; it is unexpected behavior. If you have some funky thing in your object that needs to change, like a reference count, then you should prefer declaring that one part mutable over disallowing const right-hand side expressions. You can pass a non-const value in for a const parameter, but the reverse is not true.

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