我正在阅读Programming Perl
,我发现了这个代码片段:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {
color => "bay",
legs => 4,
owner => undef,
@_, # Override previous attributes
};
return bless $self, $class;
}
new
使用像这样的构造函数,调用对象实例有什么好处?我想这就是它的用途,对吧?我的猜测是,如果有人想编写这样的构造函数,他将不得不添加更多代码,将第一个对象的属性复制到即将创建的对象。