一类的重载运算符 [英] Overloading operators for a class
问题描述
假设我有以下课程:
class A {
has $.val;
method Str { $!val ~ 'µ' }
}
# Is this the right way of doing it?
multi infix:<~>(A:D $lhs, A:D $rhs) {
('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}
如何以与上一类中的Str
相同的方式重载类的运算符(例如,+
)?
How would I overload an operator (e.g., +
) for a class in the same manner as Str
in the previous class?
我猜想这仅适用于在实例对象上调用的方法,并且对操作员使用multi operator-type:<OP>(T $lhs, T $rhs) { }
语法是实现此目的的正确方法,但我不确定.
I guess this only works for methods that are invoked on an instance object and using the multi operator-type:<OP>(T $lhs, T $rhs) { }
syntax for operators is the right way to go about it but I'm unsure.
例如,在Python中,以运算符(例如operator.__add__
)命名的特殊方法和运算符(例如+
)之间似乎存在对应关系.此外,自定义类的任何运算符重载都在该类内部完成.
For instance, in Python there seems to be a correspondence between special methods named after the operators (e.g., operator.__add__
) and the operators (e.g., +
). Furthermore, any operator overloading for a custom class is done inside the class.
推荐答案
在Perl 6中,运算符被视为当前语言的一部分.与当前语言相关的所有事物均以词法定义(即my
范围).因此,multi
子是正确的用法.
In Perl 6, operators are considered part of the current language. All things that relate to the current language are defined lexically (that is, my
-scoped). Therefore, a multi
sub is the correct thing to use.
如果将此代码放在模块中,您可能还想用is export
为操作员标记multi
:
If putting this code in a module, you would probably also want to mark the multi
for the operator with is export
:
multi infix:<~>(A:D $lhs, A:D $rhs) is export {
('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}
以便对use
或import
模块的用户可用(实际上use
是根据import
定义的,而import
将符号导入词法范围).
So that it will be available to users who use
or import
the module (use
is in fact defined in terms of import
, and import
imports symbols into the lexical scope).
虽然默认情况下有一些运算符委托给方法(例如,prefix:<+>
调用Numeric
),但两者之间没有1:1关系,并且对于大多数运算符,其实现直接在运算符multi sub
上).
While there are some operators that by default delegate to methods (for example, prefix:<+>
calls Numeric
), there's no 1:1 relation between the two, and for most operators their implementation is directly in the operator sub
(or spread over many multi sub
s).
此外,运算符集是开放的,因此,不仅限于重载现有运算符,还可以引入新的运算符.当操作符的新含义与所使用符号的常规语义没有明确关联时,鼓励使用此方法.例如,重载+
进行矩阵加法是明智的,但是对于某些可能不被视为加法的事物,新的运算符将是一个更好的选择.
Further, the set of operators is open, so one is not restricted to overloading existing operators, but can also introduce new ones. This is encouraged when the new meaning for the operator is not clearly related to the normal semantics of the symbol used; for example, overloading +
to do matrix addition would be sensible, but for something that couldn't possibly be considered a kind of addition, a new operator would be a better choice.
这篇关于一类的重载运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!