【发布时间】:2013-06-24 00:55:51
【问题描述】:
我不知道这是否可能,但我想从 Perl 中调用一个已知的子类函数。我需要一些“通用”的东西来称呼更具体的东西。我的超类将假定它的子类的所有类都定义了一个已知函数。我猜这类似于Java“实现”。
例如,假设我有以下代码:
GenericStory.pm
package Story::GenericStory;
sub new{
my $class = shift;
my $self = {};
bless $self, class;
return $self;
}
sub tellStory {
my $self;
#do common things
print "Once upon a time ". $self->specifics();
}
#
Story1.pm
package Story::Story1;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
my $self;
print " there was a dragon\n";
}
#
Story2.pm
package Story::Story2;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
print " there was a house\n";
}
#
MAIN
my $story1 = Story::Story1->new();
my $story2 = Story::Story2->new();
#Once upon a time there was a dragon.
$story1->tellStory();
#Once upon a time there was a house.
$story2->tellStory();
编辑:
代码运行良好。我只是忘记了“我的 $self = shift;”在tellStory()中;
【问题讨论】:
-
use warnings;应该明白这一点
标签: perl class oop subclass superclass