一元负重载:成员还是非成员?
鉴于前缀一元运算符可以“由不带参数的非静态成员函数或带一个参数的非成员函数实现”(§13.5.1[over.unary]/1),除了适用于任何成员/非成员函数选择的通常封装/代码重用设计原理之外,还有什么区别吗?
对于二元运算符,存在语义差异,因为非-成员允许对其左侧操作数进行隐式转换。一元运算符似乎没有类似的东西,但标准将 std::complex
的一元否定运算符定义为非成员(§26.4.6[complex.ops] ),而 std::valarray
和 std::duration
的一元否定运算符是成员(§26.6.2.6[valarray.unary],§20.11.5.3[time.duration.arithmetic])。有细微差别吗?
Given that prefix unary operators can be "implemented by a non-static member function with no parameters or a non-member function with one parameter" (§13.5.1[over.unary]/1), is there a difference besides the usual encapsulation/code reuse design rationales that apply to any member/non-member function choices?
For binary operators, there's a semantic difference because non-members allow implicit conversions of their left-hand operands. There doesn't seem to be anything like that for the unary operators, yet the standard defines std::complex
's unary negation operator as a non-member (§26.4.6[complex.ops]), while std::valarray
's and std::duration
's unary negation operators are members (§26.6.2.6[valarray.unary], §20.11.5.3[time.duration.arithmetic]). Is there a nuance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,与决定非运算符函数应该是成员还是非成员相比没有区别。显然,如果可能的话,更喜欢非成员、非朋友(就像标准算法一样)。
As far as I'm aware there are no differences as compared to deciding if a non-operator function should be member or non-member. Obviously prefer non-member, non-friend when possible (like the standard algorithms).
尽可能使用会员更有意义,因为您不必与朋友一起疯狂。但除此之外,这只是代码风格的决定。
Using members when possible makes more sense, since you don't have to go crazy with friends. But otherwise, it is just a code style decision.