Swift编程:多态、类型转换、值类型与引用类型及属性详解
1. 多态与类型转换
多态意味着“有多种形式”,例如每个僵尸(Zombie)也是怪物(Monster),因为僵尸继承自怪物,所以可以把僵尸实例当作怪物来处理,反之亦然,但只有一种做法是安全的。
let fredTheZombie: Monster = Zombie()
fredTheZombie.town = myTown
fredTheZombie.terrorizeTown()
fredTheZombie.town?.printDescription()
这里声明 fredTheZombie 为 Monster 类型,但存储的是 Zombie 实例。编译器根据声明的变量类型来判断后续操作是否允许。只要只对变量进行怪物相关的操作,编译器就会认为没问题。
然而,如果尝试访问仅存在于 Zombie 的属性,如 walksWithLimp ,会产生编译错误:
let fredTheZombie: Monster = Zombie()
fredTheZombie.town = myTown
fredTheZombie.terrorizeTown()
fredTheZombie.town?.printDescription()
fredTheZombie.walksWithLimp = true
超级会员免费看
订阅专栏 解锁全文
9

被折叠的 条评论
为什么被折叠?



