代码之家  ›  专栏  ›  技术社区  ›  humbleCoder

超类和子类——方法使用

  •  1
  • humbleCoder  · 技术社区  · 7 年前

    所以我对学习objective-C和面向对象编程一般来说是新手。我一直在看Udemy的一些视频,不太了解子类是如何工作的。他创建了一个名为“Vehicle”的cocoa touch类,它是“Viewcontroller”的子类。现在,这是否意味着viewcontroller现在可以访问“Vehicle”中的方法?

    -(void)test 
    {
      self.make = @"Honda";
      self.model = @"Civic";
    }
    

    如果我在viewcontroller中执行此操作。当我创建该类的实例时,它不应该设置模型并使其符合本田和思域吗?

    vehicle *civic1 = [[vehicle alloc]init];
    
    NSLog(@"print out the make and model: %@ and %@", civic1.make, 
    civic1.model);
    

    相反,两者的打印结果均为空。为什么会这样?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Marcio Romero Patrnogic    7 年前

    这两个属性都为零,因为您从未调用“test”函数。

    vehicle *civic1 = [[vehicle alloc]init];
    //here the call
    [civic1 test];
    //
    NSLog(@"print out the make and model: %@ and %@", civic1.make, 
    civic1.model);
    

    下一个问题是,您正在创建车辆实例,而不是Civic实例。由于考试是公民课的一种方法,你不允许调用这种方法。

    选项1

    vehicle *civic1 = [[civic alloc]init]; //pointer to a vehicle.. but creating a civic
    //here the call
    [((civic*)civic1) test]; //typecast the vehicle pointer to use it as the civic it is
    //
    

    选项2

    civic *civic1 = [[civic alloc]init]; //civic pointer, and creating a civic
    //here the call
    [civic1 test];
    //
    
        2
  •  0
  •   glyvox    7 年前

    test 方法 Vehicle 交通工具 类必须具有要由子类重新定义的方法声明 Civic

    vehicle *civic1 = [[vehicle alloc]init];
    [civic1 test];
    NSLog(@"print out the make and model: %@ and %@", civic1.make, 
    civic1.model);
    

    希望这有帮助。