8

我最近开始使用模块MooseX::Declare。我喜欢它的语法。它优雅而整洁。有没有人遇到过您想在一个类中编写许多函数(其中一些很大)并且类定义运行到页面中的情况?是否有任何解决方法可以使类定义仅在类外部声明函数和真正的函数定义?

我正在寻找的是这样的 -

class BankAccount {
    has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
    # Functions Declaration.
    method deposit(Num $amount);
    method withdraw(Num $amount);
}

# Function Definition.
method BankAccount::deposit (Num $amount) {
    $self->balance( $self->balance + $amount );
}

method BankAccount::withdraw (Num $amount) {
    my $current_balance = $self->balance();
    ( $current_balance >= $amount )
    || confess "Account overdrawn";
    $self->balance( $current_balance - $amount );
}

我可以看到有一种方法可以使类可变。有谁知道该怎么做?

4

2 回答 2

7

容易(但需要添加到文档中)。

class BankAccount is mutable {
}

顺便说一句,你为什么要在类之外定义你的方法?

你可以去

class BankAccount is mutable {
    method foo (Int $bar) {
         # do stuff
    }
}
于 2009-02-02T11:33:59.227 回答
0

我希望我的类定义简短,并给出类用途的抽象概念。我喜欢它在 C++ 中完成的方式,您可以选择使用范围解析运算符在内联或类外定义函数。这使得类定义简洁明了。这就是我要找的。

谢谢你的时间。

于 2009-02-03T06:12:56.987 回答