使用非成员函数重载运算符
这个问题的答案似乎让我无法回答,但是如何使用非成员函数进行重载。您是否只是创建一个程序级函数,并且无论原型(或定义)存在哪里,运算符都会为该类类型重载?
The answer to this question seems to escape me, but how do you go about overloading with non-member functions. Do you just create a program level function and where ever the prototype (or definition) exists the operator is overloaded for that class type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于成员函数,
this
将是左侧参数,这意味着您的运算符只有一个参数(对于一元运算符则没有)。对于独立函数,您必须分别为二元或一元运算符提供两个或一个参数。一个很好的例子是流的
<<
运算符:这里,
os
是左侧参数,val
是右手边一个。至于“where”,必须在使用它的地方定义该运算符。一般来说,将它们放在与您要重载运算符的类型相同的位置。
编辑:
对于重要的运算符(基本类型的算术运算),运算符是函数调用的语法糖。当你这样做时:
就像写:
但更具可读性。
对于成员运算符,左侧参数将为
this
(这就是成员运算符少一个参数的原因)。With a member function,
this
would be the left hand side parameter, meaning your operator would only have one argument (or none for unary operators). With a freestanding function, you must supply either two or one arguments for binary or unary operators, respectively.A good example is the
<<
operator for streams:Here,
os
is the left hand side parameter, andval
is the right hand side one.As for "where", the operator must be defined where you use it. Generally, put them at the same place as the type you're overloading the operators for.
EDIT:
For non trivial operators (arithmetic operations on primitive types), operators are syntactic sugar for function calls. When you do this:
It's like writing that:
But more readable.
For member operators, the left parameter will be
this
(and that's why member operators have one less argument).