Overloaded operators: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: revise code layout to emphasize parallelism) |
||
Line 458: | Line 458: | ||
so that they can be used on members of that class(package). Also see 'Zeckendorf arithmetic' where overloading |
so that they can be used on members of that class(package). Also see 'Zeckendorf arithmetic' where overloading |
||
is used on Zeckendorf numbers. |
is used on Zeckendorf numbers. |
||
<syntaxhighlight lang="perl"> |
<syntaxhighlight lang="perl">use v5.36; |
||
use strict; # https://rosettacode.org/wiki/Overloaded_operators |
|||
use warnings; |
|||
⚫ | |||
my $y = Ones->new( 4 ); |
|||
my $z = $x + $y; |
|||
⚫ | |||
$z = $x - $y; |
|||
⚫ | |||
$z = $x * $y; |
|||
print "$x * $y = $z\n"; |
|||
$z = $x / $y; |
|||
print "$x / $y = $z\n"; |
|||
package Ones; |
package Ones; |
||
use overload qw("" asstring + add - subtract * multiply / divide); |
use overload qw("" asstring + add - subtract * multiply / divide); |
||
sub new ( $class, $value ) { bless \('1' x $value), ref $class || $class } |
|||
sub new |
|||
sub asstring ($self, $other, $) { $$self } |
|||
{ |
|||
sub asdecimal ($self, $other, $) { length $$self } |
|||
my ( $class, $value ) = @_; |
|||
bless \( |
sub add ($self, $other, $) { bless \($$self . $$other), ref $self } |
||
⚫ | |||
} |
|||
⚫ | |||
⚫ | |||
sub asstring |
|||
{ |
|||
my ($self, $other, $swap) = @_; |
|||
$$self; |
|||
} |
|||
sub asdecimal |
|||
{ |
|||
my ($self, $other, $swap) = @_; |
|||
length $$self; |
|||
} |
|||
sub add |
|||
{ |
|||
my ($self, $other, $swap) = @_; |
|||
bless \($$self . $$other), ref $self; |
|||
} |
|||
sub subtract |
|||
{ |
|||
my ($self, $other, $swap) = @_; |
|||
⚫ | |||
} |
|||
package main; |
|||
sub multiply |
|||
{ |
|||
my ($self, $other, $swap) = @_; |
|||
⚫ | |||
} |
|||
⚫ | |||
sub divide |
|||
⚫ | |||
{ |
|||
$z = $x - $y; say "$x - $y = $z"; |
|||
⚫ | |||
⚫ | |||
$z = $x / $y; say "$x / $y = $z";</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |