OOP perl新手...第一个程序,不是过载构造函数的打包。我尝试了很多东西,可能是我还缺少一些东西!
基类:
#!/usr/bin/perl
use strict;
package Person;
sub new
{
my($class)=shift;
my($self)={
_name=>shift,
_sname=>shift,
};
bless $self, $class;
return $self;
}
1;
派生类:
#!/usr/bin/perl
package Employee;
use strict;
use Person;
our @ISA = qw(Person);
sub new
{
my($class)=@_;
my($self)=$class->SUPER::new($_[1],$_[2]);
my $self1={
_id=>$_[3],
_sal=>$_[4],
};
bless $self1,$class;
return ($self);
}
1;
主程序:
#!/usr/bin/perl
use strict;
use Data::Dumper;
use Employee;
sub main
{
my($obj)=Employee->new("abc","def","515","10");
print Dumper $obj;
}
main();
我无法获得基类类成员的值。没有得到我想念的程序。帮助我。
答案 0 :(得分:7)
在派生的构造函数中不需要名为$self1
的对象。你应该说:
sub new {
my($class)=@_;
my($self)=$class->SUPER::new($_[1],$_[2]);
$self->{_id} = $_[3];
$self->{_sal} = $_[4];
# no need to bless -- $self is already blessed correctly in SUPER::new
return ($self);
}