Perl:强制继承模块

chr*_*s01 0 perl inheritance

我有一个Perl包(例如汽车),它是一些其他模块的基类(例如面包车,豪华轿车,敞篷车......) -

use base ("car");
Run Code Online (Sandbox Code Playgroud)

在van的pm文件中,...

我需要确保不使用汽车 - 只允许使用继承的物体(​​货车,豪华轿车,......).

今天我在基类内部使用ref().如果它返回"car"的名称,我知道它在没有继承的情况下使用,然后我退出并出现错误.

如果van,...使用ref()将返回"van",...

是否有更优雅/静态的方式来做到这一点.让我们说一种方法,我可以获得一种语法错误?

不,我不喜欢与OO语言讨论OO主题中Perl的弱点;-)

编辑: 这是一个示例.有用.

问题是,如果是更好的方式来检查car :: new.

#---------car.pm----------
package car;

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

  if(ref($self) eq "car")    # thats my check to make sure beep exists
  { die "no allowed because no beep here"; 
  }

  $return $self;
}

sub honk
{ beep ();    # only defined in the inherited class (van, ...)
}

1;


#----van.pm-----
package van;

use car;
use base ("car");

sub beep 
{
   print "tuuuut";
}
1;

#---------main.pl---------
car->new ()->honk ();   # dies
# if no ref-check it would crush because no beep in car.

van->new ()->honk ();   # ok but maybe not most elegant
Run Code Online (Sandbox Code Playgroud)

yst*_*sth 5

你没有显示你的代码,但听起来你没有在正确的地方检查; 你应该只需要在构造函数中执行此操作:

sub new {
    my ($class, @other_args) = @_;
    if ($class eq __PACKAGE__) {
        Carp::croak "must be subclassed";
    }
Run Code Online (Sandbox Code Playgroud)

但不,没有办法在编译时这样做.

  • @chris:这段代码比你的版本更快地短路.它避免了在检查类之前创建对象的需要.它检查对象将成为的类,如果您要创建抽象类的对象,它将死亡. (2认同)