关于运算符重载定义中的 const
对于下面的定义
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
参数中的 const 引用意味着您不会更改 v,因此您可以将常量向量(和临时变量!)传递给函数。这是一件好事。
恒定的按值回报是一种噱头。它阻止你写这样的东西:
不过,按值返回常量是有问题的,因为它干扰了 C++11 的右值引用和移动语义:
正因为如此,而且因为像我上面展示的那样的滥用是相当严重的不太可能偶然发生,因此最好仅按非常数的值返回。
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:
Returning by-value as constant is problematic, though, since it interferes with C++11's rvalue references and move semantics:
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.
第一个 const 表示返回值是常量且不能更改(顺便说一句,这对于乘法运算符来说是一个坏主意):
第二个 const 表示参数“v”是常量:
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):
The second const indicates that the argument "v" is constant: