D语言接口

接口是迫使从它继承的类必须实现某些功能或变量的方法。函数不能在一个接口来实现,因为它们在从接口继承的类总是执行。使用interface关键字代替,尽管两者在很多方面是相似的class关键字创建一个接口。当你想从一个接口继承和类已经从另一个类继承,那么需要单独的类的名称,并用逗号将接口的名称。

让我们来看一个简单的例子,说明使用的接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import std.stdio;
// Base class
interface Shape
{
public:
void setWidth(int w);
void setHeight(int h);
}
// Derived class
class Rectangle: Shape
{
int width;
int height;
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
int getArea()
{
return (width * height);
}
}
void main()
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
writeln("Total area: ", Rect.getArea());
}
当上面的代码被编译并执行,它会产生以下结果:
Total area: 35

Final和静态函数接口

一个接口可以有最终的和静态方法的定义应包括在接口本身。这些功能不能过度由派生类重载。一个简单的例子如下所示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import std.stdio;
// Base class
interface Shape
{
public:
void setWidth(int w);
void setHeight(int h);
static void myfunction1()
{
writeln("This is a static method");
}
final void myfunction2()
{
writeln("This is a final method");
}
}
// Derived class
class Rectangle: Shape
{
int width;
int height;
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
int getArea()
{
return (width * height);
}
}
void main()
{
Rectangle rect = new Rectangle();
rect.setWidth(5);
rect.setHeight(7);
// Print the area of the object.
writeln("Total area: ", rect.getArea());
rect.myfunction1();
rect.myfunction2();
}
让我们编译和运行上面的程序,这将产生以下结果:
Total area: 35
This is a static method
This is a final method
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3