zoukankan      html  css  js  c++  java
  • perl 使用SUPER类来访问覆盖的方法

    有时候,你希望一个衍生类的方法表现得象基类中的某些方法的封装器
    
    
    
    这就是 SUPER 伪类提供便利的地方。它令你能够调用一个覆盖了的基类方法,而不用声明 是哪个类定义了该方
    法。(注:不要把这个和第十一章的覆盖 Perl 的内建函数的机制混淆 了,那个不是对象方法并且不会被继承覆
    盖。你调用内建函数的覆盖是通过 CORE 伪包,而 不是 SUPER 伪包。)下面的子过程在当前包的 @ISA 里查
    找,而不会要求你声明特定类:
    
    
    [root@wx03 test]# cat Horse.pm 
    
    当前类:
    
    package Horse;
    our @ISA = "Critter";
    sub new {
    my $invocant = shift;
    my $class = ref($invocant) || $invocant;
    my $self = {
    color => "bay",
    legs => 4,
    owner => undef,
    @_, # 覆盖以前的属性
    };
    return bless $self, $class;
    };
    sub sum1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a + $b + 7;
    };
    1;
    
    
    [root@wx03 test]# cat Critter.pm 
    
    基类:
    
    package Critter;
    sub new {
        my $self = {};
        my $invocant = shift;    
    my $class = ref($invocant) || $invocant;
    	my ($name)=@_;    
          my $self = {    
             "name" =>$name    
                     };  
        bless $self, $class; # Use class name to bless() reference
        return $self;
    
    };
    
    sub sum1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a + $b;
    };
    
    
    sub fun1 {
           $self=shift;
           my $a=shift;
           my $b=shift;
           return $a / $b;
    }
    1;
    
    
    [root@wx03 test]# cat t6.pl 
    unshift(@INC,"/root/test"); 
    use Horse;;
    use base qw(Critter);
    require Critter;
    use Data::Dumper;
    $ed = Horse->new; # 四腿湾马
    print $ed->sum1(4,5);
    print "
    ";
    print $ed->sum1(4,5);
    print "
    ";
    
    [root@wx03 test]# perl t6.pl 
    16
    16
    
    
    此时由于当前包的方法覆盖了基类的方法 所以都是16
    
    
    
    
    [root@wx03 test]# cat t6.pl 
    unshift(@INC,"/root/test"); 
    use Horse;;
    use base qw(Critter);
    require Critter;
    use Data::Dumper;
    $ed = Horse->new; # 四腿湾马
    print $ed->sum1(4,5);
    print "
    ";
    print $ed->SUPER::sum1(4,5);
    print "
    ";
    [root@wx03 test]# perl t6.pl 
    16
    9
    
    这时候会访问覆盖的方法

  • 相关阅读:
    Deployment of VC2008 apps without installing anything
    用MT.exe将exe中的manifest文件提取出来和将manifest文件放入exe中
    Golang快速入门
    8个优质的编程学习网站
    免费学编程!10个全球顶尖的编程在线自学网站
    7个在线学习C++编程的最佳途径
    为什么多数游戏服务端是用 C++ 来写
    学习游戏服务器开发必看,C++游戏服务器开发常用工具介绍
    Ambari——大数据平台的搭建利器(一)
    Python爬虫项目整理
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13350783.html
Copyright © 2011-2022 走看看