3
是否有可能在Perl中创建一个没有实现构造函数的子类?我不需要任何特定于子类的构造函数行为,所以我想从父类继承。我可以在不实现子构造函数的情况下创建Perl子类吗?
在这个例子中,我有一个基类Base.pm
和一个子类Child.pm
。该Child
类应该简单地覆盖在其父的方法之一:
# test.pl
use strict;
use warnings;
use Child;
my $o = Child->new();
$o->exec();
-
# Base.pm
package Base;
sub new{
my $self = {};
bless $self;
return $self;
}
sub exec{
my $self = shift;
die "I'm in the Base class\n";
}
1;
-
# Child.pm
package Child;
use Base;
@ISA = ('Base');
sub exec{
my $self = shift;
die "OVERRIDE in child\n";
}
1;
当我运行test.pl中,基类的 exec方法得到执行(我假设这是因为该对象在构造函数Base.pm
中被祝福为Base
)。
$ ./test.pl
I'm the Base class
有没有一种方法来实现一个子类而不必重新构造一个构造函数?
另请参见['继承 - 在perlobj中编写构造函数](http://perldoc.perl.org/perlobj.html#Writing-Constructors) – zdim