接 口 2.014

接口声明:
interface 标识符 接口体
interface 标识符 :上层接口 接口体
上层接口
标识符
标识符 , 上层接口

接口体:
{ 多个声明定义 }

接口(Interface)描述的是继承自某个接口的类所必须实现的一系列函数。一个接口的实现类可以被转换成对该接口的引用。接口相当于操作系统对象,如 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() { } // 正确,提供了实现
}
class B : D
{
int foo() { } // 错误,没有提供 void foo() 实现
}

接口可以被继承,其中的函数可以被重写:

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; // 正确,因为 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()

[color=red]2.014
Const and Invariant Interfaces

If an interface has const or invariant storage class, then all members of the interface are const or invariant. This storage class is not inherited. [/color]
13.1 COM 接口

接口的一个变体是 COM 接口。按照设计,COM 接口被为直接映射到 Windows COM 对
象。任何 COM 对象都由一个 COM 接口表示,任何带有 COM 接口的 D 对象都可以被外
部 COM 客户端使用。

按定义,COM 接口从 std.c.windows.com.IUnknown 接口派生。

COM 接口与普通 D接口的不同之处在于:
• 它从 std.c.windows.com.IUnknown 接口派生。
• 它不能成为 Delete表达式 的参数。
• 引用不能向上转型为封闭的类对象,也不能向下转型为从它派生的接口。为了达到这
个目的,必须按照标准的 COM 风格为接口实现一个合适的 QueryInterface()
方法。


。。。。。。。。。。。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值