构造器重载
更新:HHH   时间:2023-1-7


一、构造器重载概念

        函数重载概念也适用于构造器,条件如下:

    1、函数有相同的名字‘

    2、参数列表不同或返回值类型不同;


    构造器满足以下2个条件:

    

class 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.width=length
                    self.height=length
}
                init(){
                    width = 10.0
                    height = 20.0
}
}




二、值类型构造器类型

        

            为了减少多个构造器间的代码重复,在定义构造器时,可以通过调用其它的构造器来完成实例的构造部分,这个过程称为构造器代理。构造器代理在值类型和引用类型中使用不同,

            

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.init(width:width,height:height)
}
                
                init(length:Double){
                    self.init(width:length,height:length)
}
                init(){
                    self.init(width:60,height:80)
}
}


三、引用类型构造器横向代理


            引用类型构造器代理是类构造器代理,由于类有继承关系,类构造器代理比较复杂,分为横向代理和向上代理


            1、横向代理类型类似于值类型构造器代理,发生在同一类内部,这种构造器称为便利构造器;

             2、向上代理发生在继承情况下,在子类型构造过程中要先调用父类构造器,初始化父类的存储属性,这种构造器称为指定构造器。


class 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
}
                
                convenience init(length:Double){
                    self.init(W:length,H:length)
}
                 convenience init(){
                    self.init(length:10.0)
                    self.height = 20.0
}
}


返回开发技术教程...