zoukankan      html  css  js  c++  java
  • [Objective-c 基础

     A.对象的多种形态

    1.父类指针指向子类对象
    2.调用方法的时候,会动态监测真实地对象的方法
    3.没有继承,就没有多态
    4.好处:用一个父类指针可以指向不同的子类对象
    5.强制转换类型之后就能使用子类特有的方法,否则会出现warning(仍可以正常运行,即不论指针类型,只要对象存在实际方法就可以运行)
     1  
     2 #import <Foundation/Foundation.h>
     3 
     4 @interface Animal : NSObject
     5 - (void) eat;
     6 @end
     7 
     8 @interface Dog : Animal
     9 - (void) run;
    10 @end
    11 
    12 @interface Cat : Animal
    13 
    14 @end
    15 
    16 
    17 @implementation Animal
    18 - (void) eat
    19 {
    20     NSLog(@"吃东西---");
    21 }
    22 
    23 @end
    24 
    25 @implementation Dog
    26 - (void) eat
    27 {
    28     NSLog(@"狗狗吃东西");
    29 }
    30 
    31 - (void) run
    32 {
    33     NSLog(@"狗狗跑起来了");
    34 }
    35 @end
    36 
    37 @implementation Cat
    38 
    39 - (void) eat
    40 {
    41     NSLog(@"猫猫吃东西");
    42 }
    43 
    44 @end
    45 
    46 void feed(Animal *animal)
    47 {
    48     NSLog(@"开始喂动物");
    49     [animal eat];
    50 }
    51 
    52 
    53 int main()
    54 {
    55     Animal *a = [Dog new];
    56     [a eat];
    57     Animal *c = [Cat new];
    58     [c eat];
    59    
    60     feed(a);
    61     feed(c);
    62    
    63     Dog *dog = (Dog *)a;
    64     [dog run];
    65    
    66     return 0;
    67 }
     
     
  • 相关阅读:
    access denied for user 'root'@'localhost'(using password:YES) FOR WINDOWS
    PKU 1001解题代码
    PKU 1002解题总结
    为什么vue组件data必须是函数
    call 和 apply 区别
    CSS|Stacking context 堆叠上下文
    Vue3.0 tsx 函数组件
    js中的变量提升
    JavaEE|架构
    MVC,MVP 和 MVVM
  • 原文地址:https://www.cnblogs.com/hellovoidworld/p/4119352.html
Copyright © 2011-2022 走看看