曲径通幽论坛

标题: :: 和 -> 符号的比较 [打印本页]

作者: beyes    时间: 2011-10-31 14:16
标题: :: 和 -> 符号的比较
箭头 -> 符号一般用在具有多态性,动态绑定和继承行为的面向对象的编程中。虽然在很多情况下也可以用 :: 语法来代替,但它却比较不灵活,在一些情况下如果不用条件语句进行判断,那么还会带来问题。

下面的示例展示了 :: 语法的缺点,如果使用 -> 面向对象的语法,则不会有问题。

先创建 2 个 pm 模块:Dog.pm 和 Cat.pm
Dog.pm
[code=perl]

package Dog;


sub new {
        my $class = shift;
        my $ref = {};
        return bless ($ref, $class);
}


sub set_attributes {
        my $self = shift;
        $self->{"Name"} = "Jim";
        $self->{"Talk"} = "Woof woof...";
}


sub speak {
        my $self = shift;
        print "$self->{'Talk'} I'm the cat called $self->{'Name'}.\n";
}


1;[/mw_shl_code]

Cat.pm
[code=perl]

package Cat;


sub new {
        my $class = shift;
        my $ref = {};
        return bless ($ref, $class);
}


sub set_attributes {
        my $self = shift;
        $self->{'Name'} = "Tom";
        $self->{'Talk'} = "Meow purrrr..";
}


sub speak {
        my $self = shift;
        print "$self->{'Talk'} I'm the cat called $self->{'Name'}.\n";
}


1;[/mw_shl_code]

使用上面两个模块的脚本:
[code=perl]#!/usr/bin/perl


use Cat;
use Dog;


$mydog = new Dog;
$mycat = new Cat;


$mydog->set_attributes;
$mycat->set_attributes;


#自动绑定正确
$mydog->speak;
$mycat->speak;


print "\nNow we make a mistake in passing arguments.\n\n";


#将狗对象数据传入到猫类中
Cat::speak($mydog);
[/mw_shl_code]
运行输出:
[beyes@beyes dcolon]$ ./catdog.pl
Woof woof... I'm the cat called Jim.
Meow purrrr.. I'm the cat called Tom.

Now we make a mistake in passing arguments.

Woof woof... I'm the cat called Jim.
由上输出可见,在使用 :: 时,由于传递进错误的对象,导致了猫发出了狗的叫声这种不合常理的输出。因此,在面向对象的编程中,应该使用面向对象的符号 ->




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2