先定义一个Person类
package Person ; # package name must be same as file name
sub new{ my $class = shift ; my ($name, $age) = @_ ; my $self = { "name" => $name, "age" => $age, } ; bless($self, $class) ; return $self ; }
sub set_name{ my ($self, $name) = @_ ; $self->{name} = $name ; }
sub get_name{ my $self = shift ; return $self->{name} ; }
sub set_age{ my($self, $age) = @_ ; $self->{age} = $age ; }
sub get_age{ my $self = shift ; return $self->{age} ; }
1 ;
在定义一个Employee类,继承自Person类
use Person ; package Employee ;
@ISA = qw(Person) ;
sub new{ my $class = shift ; my ($name, $age, $salary) = @_ ; my $self = Person->new($name, $age) ; $self->{salary} = $salary ; bless($self, $class) ; return $self ; }
sub get_salary{ my $self = shift ; return $self->{salary} ; }
sub set_salary{ my ($self, $salary) = @_ ; $self->{salary} = $salary ; }
sub change_salary{ my $self = shift ; my $new_salary = shift ; $self->{salary} = $new_salary ; }
1 ;
创建一个Employee对象并输出其信息,然后修改Employee的属性并再次输出信息
my $employee = Employee->new("zdd", "30", "11k") ; print $employee->get_name(), "\n" ; print $employee->get_age(), "\n" ; print $employee->get_salary(), "\n" ;
# Change age and salary $employee->set_age(35) ; $employee->set_salary("20k") ;
# print new info print $employee->get_name(), "\n" ; print $employee->get_age(), "\n" ; print $employee->get_salary(), "\n" ;
几点说明
1 继承通过将基类加入@ISA数组实现
2 类成员函数的第一个参数默认是调用者所属的类
3 get_xxx成员函数中第一行代码 $self = shift ; 不可以省略。
以上所提到的类是基于匿名哈希实现的,还有一种方法是使用数组来实现,但是比较繁琐,具体看这里
http://club.topsage.com/thread-422598-1-1.html
|
请发表评论