背景:
讲到面向对象,不能只写出个类然后调用,根本优势在于继承来重用代码.Perl的继承虽然功能少些但简单实用.
正文:
父类, Person.pm
package Person; #包名, 最好与文件名相同
use Exporter; #父类必须
@ISA = qw(Exporter); #父类必须
@EXPORT = qw(setName); #父类必须,释放出该成员方法,以便继承
sub new{ my $this = {}; #本质是一个哈希引用(指针),哈希是其成员列表,初始为空
my $type = shift; #接收第一个参数,类名
my %parm = @_; #接收全部参数到一个哈希
$this->{'Name'} = $parm{'Name'}; #初始化各成员变量
$this->{'Age'} = $parm{'Age'}; bless $this, $type; #祝福给$type,此处是自己
return $this; #返回对象
}
sub setName{ my $this = shift; #接收第一个参数,对象本身,在包外调用
$this->{'Name'} = shift; #开始接收其他参数
print "call Person setName.\n"; } 1; #重点,包结尾
|
子类, Man.pm
package Man; use Person; #使用父类
use Exporter; #子类非必须
@ISA = qw(Exporter, Person); #子类非必须
#@EXPORT = qw(setName);
sub new{ my $type = shift; my $this = new Person('Name'=>"MJ", 'Age'=>50); #这就是继承,哈希里有了父类的成员
bless $this, $type; return $this; }
sub setName{ #重载,父子类均有该函数了
my $this = shift; $this->{'Name'} = shift; print "call Man setName.\n" } 1;
|
调用, callClass.pl
use Person; use Man; use strict;
#Person obj $jack
my $jack = new Person('Name'=>"jack wang", 'Age'=>23); print "First Person Name:".$jack->{'Name'}."\n"; #Man obj $mj
my $mj = new Man; print "First Man Name:".$mj->{'Name'}."\n";
$jack->setName("Blue zheng"); #父类setName
print "Second Person Name:".$jack->{'Name'}."\n"; print "Second Man Name:".$mj->{'Name'}."\n"; $mj->setName("KB"); #子类setName,如果子类没有重载,则调用父类setName
print "Third Person Name:".$jack->{'Name'}."\n"; print "Third Man Name:".$mj->{'Name'}."\n"; $mj->Person::setName("WD"); #强行调用父类setName
print "Forth Person Name:".$jack->{'Name'}."\n"; print "Forth Man Name:".$mj->{'Name'}."\n";
|
我想,这段代码对于刚写第一个面向对象的perl程序的人会有帮助的.
阅读(548) | 评论(1) | 转发(0) |