println("长方形4:(rectc4.width) x (rectc4.height)")
上述代码第①~④行定义了4个构造器,其他是重载关系。从参数个数和参数类型上看,第①行和第②行的构造器是一样的,但是它们的外部参数名不同,所以在第⑤行调用的是第①行的构造器,第⑥行调用的是第②行的构造器。
第③行和第④行的构造器参数个数与第①行不同,所以在第⑦行调用的是第③行的构造器,第④行调用的是第⑧行的构造器。
二、值类型构造器代理
为了减少多个构造器间的代码重复,在定义构造器时,可以通过调用其他构造器来完成实例的部分构造过程,这个过程称为构造器代理。构造器代理在值类型和引用类型中使用方式不同,本节我们先介绍值类型构造器代理。
将上一节的示例修改如下:
复制代码
struct Rectangle {
var width : Double
var height : Double
init(width : Double, height : Double) { ①
self.width = width
self.height = height
}
init(W width : Double,H height : Double) { ②
self.width = width
self.height = height
}
init(length : Double) { ③
self.init(W : length, H : length)
}
init() { ④
self.init(width: 640.0, height: 940.0)
}
}
var rectc1 = Rectangle(width : 320.0, height : 480.0) ⑤
println("长方形:(rectc1.width) x (rectc1.height)")
var rectc2 = Rectangle(W : 320.0, H : 480.0) ⑥
println("长方形:(rectc2.width) x (rectc2.height)")
var rectc3 = Rectangle(length: 500.0) ⑦
println("长方形3:(rectc3.width) x (rectc3.height)")








