关于运算符重载定义中的 const

发布于 2024-12-09 14:05:41 字数 140 浏览 0 评论 0原文

对于下面的定义

const vector3F operator*(const vector3F &v, float s);

有两个const,它们各自的用法是什么?

For the following definition of

const vector3F operator*(const vector3F &v, float s);

There are two const, what are their respective usages?

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

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

发布评论

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

评论(2

薄荷港 2024-12-16 14:05:41

参数中的 const 引用意味着您不会更改 v,因此您可以将常量向量(和临时变量!)传递给函数。这是一件好事。

恒定的按值回报是一种噱头。它阻止你写这样的东西:

 vector3F v = get_vector();
 vector3F w = v;

 (v * 1.5) = w; // outch! Cannot assign to constant, though, so we're good.

不过,按值返回常量是有问题的,因为它干扰了 C++11 的右值引用和移动语义:

 move_me(v * 1.5);  // cannot bind to `vector3F &&` :-(

正因为如此,而且因为像我上面展示的那样的滥用是相当严重的不太可能偶然发生,因此最好仅按非常数的值返回。

The const-reference in the argument means that you don't change v, so you can pass constant vectors (and temporaries!) to the function. That's a Good Thing.

The constant by-value return is sort of a gimmick. It prevents you from writing things like this:

 vector3F v = get_vector();
 vector3F w = v;

 (v * 1.5) = w; // outch! Cannot assign to constant, though, so we're good.

Returning by-value as constant is problematic, though, since it interferes with C++11's rvalue references and move semantics:

 move_me(v * 1.5);  // cannot bind to `vector3F &&` :-(

Because of that, and because an abuse like the one I showed above is fairly unlikely to happen by accident, it's probably best to return by value only as non-constant.

也只是曾经 2024-12-16 14:05:41

第一个 const 表示返回值是常量且不能更改(顺便说一句,这对于乘法运算符来说是一个坏主意):

const Vector3F v = myvector*100.0;

v.x = 0; // error: the vector is constant and can not be altered

第二个 const 表示参数“v”是常量:

const vector3F operator*(const vector3F &v, float s)
{
    v.x = 0; // error: "v" is constant
}

The first const indicates that the return value is constant and can not be altered (which, by the way, is a bad idea for the multiplication operator):

const Vector3F v = myvector*100.0;

v.x = 0; // error: the vector is constant and can not be altered

The second const indicates that the argument "v" is constant:

const vector3F operator*(const vector3F &v, float s)
{
    v.x = 0; // error: "v" is constant
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文