zoukankan      html  css  js  c++  java
  • objectivec 多态 ——动态类型 id 的使用(与 C# 的比较说明)

    在C#中,我们用接口来实现多态。比如接口IOb,定义了1个方法F; 有两个类A,B都实现了IOb接口。

    IOb item = new A();

    item.F();//执行的是A.F();

    item = new B();

    item.F();//执行的B.F();

    在objective-c中,interface 的含义和C#有了很大的不同,不能这样使用。

    那么如何实现类似的效果呢。那就是特殊类型id,看如下代码段,注释:Fraction 和 Complex都包含print 方法。

    #import “Fraction.h”
    #import “Complex.h”
    int main (int argc, char *argv[])
    {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    id dataValue;//定义了一个id 类型变量
    Fraction *f1 = [[Fraction alloc] init];
    Complex *c1 = [[Complex alloc] init];
    [f1 setTo: 2 over: 5];
    [c1 setReal: 10.0 andImaginary: 2.5];
    // first dataValue gets a fraction
    dataValue = f1;
    [dataValue print]; //调用Fraction的 print方法
    // now dataValue gets a complex number
    dataValue = c1;
    [dataValue print]; //调用Complex的 print方法

    [c1 release];
    [f1 release];
    [pool drain];
    return 0;
    }

     

     


  • 相关阅读:
    iperf使用
    性能工具--vtune
    Android广告轮播图实现
    自定义控件学习——下拉刷新ListView
    JVM读书笔记
    自定义控件学习——仿qq侧滑栏
    初步使用RecyclerView实现瀑布流
    自定义Toast
    自定义对话框加状态选择器
    自定义组合控件
  • 原文地址:https://www.cnblogs.com/54007/p/1951355.html
Copyright © 2011-2022 走看看