快速覆盖子类的问题

时间:2018-10-12 17:54:44

标签: swift

我无法快速覆盖上一堂课。按照班上的指示

  
      
  1. 使用以下条件创建“汽车”类:

         
        
    • a。属性(5)

    •   
    • year –由初始值设定项初始化

    •   
    • make –由初始化程序初始化
    •   
    • 模型-由初始化程序初始化
    •   
    • 颜色-由初始值设定项初始化
    •   
    • currentSpeed –由初始化程序初始化为0
    •   
  2.   
     

创建一个继承自Car类的“ Batmobile”子类

     
      
  • 属性将保持不变

  •   
  • 功能

  •   
  • 重写init()函数,使其仅接受年份作为输入,其余属性应自动初始化为   例如:

         
        
    • make – Bat Automotive

    •   
    • 模型–蝙蝠车

    •   
    • 颜色-黑色

    •   
    • currentSpeed – 100

    •   
  •   

这些是我创建的类声明: 汽车:

class Car {
    //properties of cars
    var year : Int
    var make : String
    var model : String
    var color : String
    var currentSpeed : Int

    //functions of cars
    init(year : Int = 0, make : String, model : String , color : String , currentSpeed : Int = 0) {
        self.year = year
        self.make = make
        self.model = model
        self.color = color
        self.currentSpeed = currentSpeed
    }
}

蝙蝠车:

class Batmobile : Car {
    override init(year: Int) {
        self.year = year
        self.make = "Bat Automotive"
        self.model = "Bat Mobile"
        self.color = "Black"
        self.currentSpeed = 100
    }
}

当我尝试使用以下方法创建Batmobile对象时:

var myBatmobile = Batmobile(year: 2018)

我收到以下错误:

  

调用中缺少参数“ make”的参数

我不确定应该将哪些内容传递给Batmobile类以使其正确初始化。我的印象是,覆盖初始化函数会将所有继承的字段替换为我提供的字符串。

1 个答案:

答案 0 :(得分:1)

这样做:

class Batmobile : Car {
    init(year: Int) {
        super.init(year: year,
                   make: "Bat Automotive",
                   model: "Bat Mobile",
                   color: "Black",
                   currentSpeed: 100)
    }
}
相关问题