【问题标题】:Can I make a Perl subclass without implementing a child constructor?我可以在不实现子构造函数的情况下创建 Perl 子类吗?
【发布时间】:2016-11-04 09:11:35
【问题描述】:

在 Perl 中是否可以在不实现构造函数的情况下创建子类?我不需要任何特定于子类的构造函数行为,所以我想从父类继承。

在这个例子中,我有一个基类Base.pm 和一个子类Child.pmChild 类应该简单地覆盖其父方法之一:

# 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

有没有办法实现子类而不必重新实现构造函数?

【问题讨论】:

标签: perl


【解决方案1】:

是的。

你实际上有以下几点:

sub new {
   return bless({});
}

将其替换为以下内容:

sub new {
   my $class = shift;
   return bless({}, $class);
}

基本上,始终使用bless 的两个参数形式。


我如何编写构造函数:

  • 基类:

    sub new {
       my ($class, ...) = @_;
       my $self = bless({}, $class);
       $self->{...} = ...;
       return $self;
    }
    
  • 派生类:

    sub new {
       my ($class, ...) = @_;
       my $self = $class->SUPER::new(...);
       $self->{...} = ...;
       return $self;
    }
    

我喜欢对称。

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多