如何在Perl中用子元素覆盖父类函数? [英] How can I override a parent class function with child one in Perl?

查看:62
本文介绍了如何在Perl中用子元素覆盖父类函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换子类中的父函数(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中用子元素覆盖父类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆