gpt4 book ai didi

perl - 从父类(super class)调用已知的子类函数?

转载 作者:行者123 更新时间:2023-12-02 21:58:38 25 4
gpt4 key购买 nike

我不知道这是否可行,但我想从 Perl 调用一个已知的子类函数。我需要一些“通用”的东西来调用更具体的东西。我的父类(super class)将假设它的子类的所有类都定义了一个已知的函数。我想这类似于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();

编辑:

代码运行良好。我只是忘记了“my $self = shift;”在tellStory()中;

最佳答案

您的代码按原样工作正常(模小错误);您可能想添加父类(super class):

sub specifics {
require Carp;
Carp::confess("subclass does not implement required interface");
}

或类似的。

关于perl - 从父类(super class)调用已知的子类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17327636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com