发新话题
打印

15 D语言 接口 Interfaces

15 D语言 接口 Interfaces

知识若不分享 实在没有意义 http://www.d-programming-language-china.org 20070423

点击下面网址查看原文:
http://www.d-programming-language-china.org

by: uFramer D语言论坛 http://www.d-programming-language-china.org
from: http://www.digitalmars.com/d/interface.html
version: 基于D 1.013 (Apr 19, 2007)

QUOTE:
接口声明:
        interface 标志符 接口体
        interface 标志符 : 父接口 接口体

    父接口:
        标志符
        标志符 , 父接口

    接口体:
        { 声明定义 }

    InterfaceDeclaration:
        interface Identifier InterfaceBody
        interface Identifier : SuperInterfaces InterfaceBody

    SuperInterfaces
        Identifier
        Identifier , SuperInterfaces

    InterfaceBody:
        { DeclDefs }

接口描述了从接口派生的类必须实现的函数的列表。指向从一个接口派生的类的引用可以被转换为对这个接口的引用。接口对应于操作系统暴露的对象的接口,如 Win32 的 COM/OLE/ActiveX 。
接口不能从类派生,只能从其他接口派生。类不能多次从一个接口派生。

interface D
{
    void foo();
}

class A : D, D        // 错误,多重接口
{
}

不能创建接口的实例。

interface D
{
    void foo();
}

...

D d = new D();        // 错误,不能创建接口的实例

接口成员函数不能有实现。

interface D
{
    void bar() { }        // 错误,不允许实现
}

继承接口的类必须实现接口中的所有函数:

interface D
{
    void foo();
}

class A : D
{
    void foo() { }    // ok,提供了实现
}

class B : D
{
    int foo() { }    // 错误,没有提供 void foo() 实现
}

接口可以被继承,其中的函数可以被重写:( 本文出处: http://www.d-programming-language-china.org )

interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A
{
    int foo() { return 2; }
}
...

B b = new B();
b.foo();        // 返回 2
D d = cast(D) b;    // ok,因为 B 继承了 A 的 D 实现
d.foo();
// 返回 2

接口可以在派生类中重新实现:

interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A, D
{
    int foo() { return 2; }
}

...

B b = new B();
b.foo();        // 返回 2
D d = cast(D) b;
d.foo();        // 返回 2
A a = cast(A) b;
D d2 = cast(D) a;
d2.foo();        // 返回 2,尽管它是 A 的 D,不是 B 的 D

如果类要重新实现接口,必须重新实现接口的所有函数,不能从父类中继承:

interface D
{
    int foo();
}

class A : D
{
    int foo() { return 1; }
}

class B : A, D
{
}        // 错误,接口 D 没有 foo()

COM Interfaces

接口的一个变体是 COM 接口。按照设计,COM 接口被为直接映射到 Windows COM 对象。任何 COM 对象都由一个 COM 接口表示,任何带有 COM 接口的 D 对象都可以被外部 COM 客户端使用。
按定义,COM 接口从 std.c.windows.com.IUnknown 接口派生。COM 接口与普通 D 接口的不同之处在于:

它从 std.c.windows.com.IUnknown 接口派生。
它不能成为 DeleteExpression 的参数。
引用不能向上转型为封装的类对象(the enclosing class object),也不能向下转型为从它派生的接口。为了达到这个目的,必须按照标准的 COM 风格为接口实现一个合适的 QueryInterface() 方法。

( lastupdate:20070426 最新文章请访问http://www.d-programming-language-china.org )

关于一大步成功社区:
yidabu提倡在交流中学习,在分享中提高
收集感兴趣的知识,写下心得,通过网络与别人一起分享
理解一点就实践一步,收获什么就分享什么,成功就是这样一点点一步步累积起来的
网络只是一个工具,只有自己身心提高才是实实在在的。d-programming-language-china.org为大家提供一个学习交流各种知识的平台

TOP

发新话题