类继承

在面向对象编程中一个最重要的概念就是继承。继承允许我们在另一个类,这使得它更容易创建和维护一个应用程序来定义一个类。这也提供了一个机会重用代码的功能和快速的实施时间。

当创建一个类,而不是完全写入新的数据成员和成员函数,程序员可以指定新的类要继承现有类的成员。这个现有的类称为基类,新类称为派生类。

继承的想法实现是有关系的。例如,哺乳动物IS-A动物,狗,哺乳动物,因此狗IS-A动物,等等。

基类和派生类:

一个类可以从多个类中派生的,这意味着它可以继承数据和函数从多个基类。要定义一个派生类中,我们使用一个类派生列表中指定的基类(ES)。一个类派生列表名称的一个或多个基类和具有形式:

class derived-class: base-class

考虑一个基类Shape和它的派生类Rectangle,如下所示:

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
import std.stdio;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
}
// Derived class
class Rectangle: Shape
{
public:
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

访问控制和继承:

派生类可以访问它的基类的所有非私有成员。因此,基类成员,不应该访问的派生类的成员函数应在基类中声明为private。

派生类继承了所有基类方法有以下例外:

  • 构造函数,析构函数和基类的拷贝构造函数。

  • 基类的重载运算符。

多层次继承

继承可以是多级的,如下面的例子。

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
import std.stdio;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
}
// Derived class
class Rectangle: Shape
{
public:
int getArea()
{
return (width * height);
}
}
class Square: Rectangle
{
this(int side)
{
this.setWidth(side);
this.setHeight(side);
}
}
void main()
{
Square square = new Square(13);
// Print the area of the object.
writeln("Total area: ", square.getArea());
}
让我们编译和运行上面的程序,这将产生以下结果:
Total area: 169
联系我们

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

Copyright © 2015-2024

备案号:京ICP备15003423号-3