0

这是我的代码

       public class TKomplex
   {
       public double real;
       public double imag;
   }

           public TKomplex ksum(TKomplex a, TKomplex b)
           {
               TKomplex res;
               res.real = a.real + b.real;
               res.imag = a.imag + b.imag;
              return (res);
           }


           public TKomplex kprod(TKomplex a, TKomplex b)
           {
               TKomplex res;
               res.real = a.real * b.real - a.imag * b.imag;
               res.imag = a.real * b.imag + a.imag * b.real;
               return (res);
           }

如何在 perl 中编写代码?如何创建一个类并将对象作为参数传递给perl中的方法?

4

1 回答 1

3

这是使用 Moo 对象的一种方法:

文件 TKomplex.pm:

package TKomplex;
use Moo;

has real => (
    is => 'rw',
);
has imag => (
    is => 'rw',
);

sub ksum {
    my ($a, $b) = @_;
    my $res = TKomplex->new;
    $res->real( $a->real + $b->real );
    $res->imag( $a->imag + $b->imag );
    return $res;
}

sub kprod {
    my ($a, $b) = @_;
    my $res = TKomplex->new;
    $res->real( $a->real * $b->real - $a->imag * $b->imag );
    $res->imag( $a->real * $b->imag + $a->imag * $b->real );
    return $res;
}

1;

示例使用:

use TKomplex;
my $val = TKomplex->new( real => 3, imag => -2 );
my $ksum = TKomplex::ksum( $val, $val );
print "real: ", $ksum->real, " imag: ", $ksum->imag, "\n";

注意 ksum 和 kprod 不是方法,它们是子程序。如果您想将它们称为类方法,请说TKomplex->ksum(...)并将它们更改为在and$class之前采用参数。$a$b

没有 Moo,删除 use Moo 和 has 子句并添加:

use strict;
use warnings FATAL => 'all';
sub new {
    my ($class, %object) = @_;
    return bless \%object, $class;
}
sub real {
    my $self = shift;
    if (@_) {
        $self->{real} = shift;
    }
    else {
        $self->{real}
    }
}
sub imag {
    my $self = shift;
    if (@_) {
        $self->{imag} = shift;
    }
    else {
        $self->{imag}
    }
}
于 2013-09-30T07:26:03.607 回答