问题描述
我想替换子类中的父函数(Somefunc),所以当我调用Main过程时,它会失败.
I would like to replace parent function (Somefunc) in child class, so when I call Main procedure it should fail.
在Perl中可以吗?
代码:
package Test;
use strict;
use warnings;
sub Main()
{
SomeFunc() or die "Somefunc returned 0";
}
sub SomeFunc()
{
return 1;
}
package Test2;
use strict;
use warnings;
our @ISA = ("Test");
sub SomeFunc()
{
return 0;
}
package main;
Test2->Main();
推荐答案
调用Test2->Main()
时,程序包名称作为第一个参数传递给被调用函数.您可以使用该参数来解决正确的功能.
When you call Test2->Main()
, the package name is passed as the first parameter to the called function. You can use the parameter to address the right function.
sub Main
{
my ($class) = @_;
$class->SomeFunc() or die "Somefunc returned 0";
}
在此示例中,$class
将为"Test2"
,因此您将调用Test2->SomeFunc()
.更好的解决方案是使用实例(即Test::new
中的bless
对象,使用$self
而不是$class
).甚至更好的方法是使用 Moose
,它可以解决Perl中的面向对象编程存在很多问题.
In this example, $class
will be "Test2"
, so you will call Test2->SomeFunc()
. Even better solution would be to use instances (i.e., bless
the object in Test::new
, use $self
instead of $class
). And even better would be to use Moose
, which solves a lot of problems with object-oriented programming in Perl.
这篇关于如何在Perl中用子元素覆盖父类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!