There are currently 5 posts.
Font size: Small - 100% (Default)▼  Content converter: No conversion▼
 
Clicks Replies
1649 4
【示例】面向对象中的多态性
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 1 Posted at: 6/5/16 21:49
<?php
// 多态性
interface Shape {
    public function calcArea();
}

// 下面两个类都实现了calcArea方法
class Rectange implements Shape {
    public $x, $y, $width, $height;
    
    public function calcArea() {
        return $this->width * $this->height;
    }
}

class Circle implements Shape {
    const PI = 3.14;
    public $x, $y, $r;
    
    public function calcArea() {
        return $this->r * $this->r * self::PI;
    }
}

// 多态性的核心思想:用基类的变量去调用子类的方法
function display_area(Shape $shape) {
    echo '该图形的面积是: ' . $shape->calcArea() . '<br>';
}

$r = new Rectange();
$r->width = 400;
$r->height = 380;
display_area($r);

$c = new Circle();
$c->r = 4.8;
display_area($c);
?>

运行结果:
该图形的面积是: 152000
该图形的面积是: 72.3456
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 2 Posted at: 6/5/16 21:53
多态性除了可以用接口实现外,还可以用抽象类来实现。
例如:
<?php
abstract class Shape {
    abstract public function calcArea();
}

class Rectange extends Shape {
    public $x, $y, $width, $height;
   
    public function calcArea() {
        return $this->width * $this->height;
    }
}

class Circle extends Shape {
    const PI = 3.14;
    public $x, $y, $r;
   
    public function calcArea() {
        return $this->r * $this->r * self::PI;
    }
}

function display_area(Shape $shape) {
    echo '该图形的面积是: ' . $shape->calcArea() . '<br>';
}

$r = new Rectange();
$r->width = 400;
$r->height = 380;
display_area($r);

$c = new Circle();
$c->r = 4.8;
display_area($c);
?>
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 3 Posted at: 6/5/16 21:56
在C++中,抽象方法是用纯虚函数来实现的。
例如
abstract public function calcArea();
在C++里面写为:
virtual void calcArea() = 0;

当然多态性也不一定要用纯虚函数,就是普通的虚函数(即基类有实现)也行:
virtual void calcArea()
{
    // do something
}
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 4 Posted at: 6/5/16 21:58
C++中如果基类的方法不声明为虚函数,那么基类的指针就只能调用基类的方法。(不能实现多态性)
如果声明为虚函数,基类的指针就能调用派生类的同名方法。(实现了多态性)
如果声明为纯虚函数,那么基类的方法就不需要在基类实现,只需要在派生类实现。
巨大八爪鱼
武林盟主 二十一级
Reply
Floor 5 Posted at: 6/5/16 22:00
在PHP中,把基类Shape定义成下面这样也是合法的:
class Shape {
    public function calcArea() {
        return 0;
    }
}
即calcArea方法在基类中也有实现。
这个就相当于C++中普通的虚函数。
Reply the post
Content:
User: You are currently anonymous.
Captcha:
Unclear? Try another one.
(Shortcut key: Ctrl+Enter)
Post Information
Clicks: 1649 Replies: 4
Author: 巨大八爪鱼
Last reply: 巨大八爪鱼
Last reply time: 6/5/16 22:00
Bar Hot Posts
Announcements