- D 编程基础
- D 编程 - 首页
- D 编程 - 概述
- D 编程 - 环境
- D 编程 - 基本语法
- D 编程 - 变量
- D 编程 - 数据类型
- D 编程 - 枚举
- D 编程 - 字面量
- D 编程 - 运算符
- D 编程 - 循环
- D 编程 - 条件语句
- D 编程 - 函数
- D 编程 - 字符
- D 编程 - 字符串
- D 编程 - 数组
- D 编程 - 关联数组
- D 编程 - 指针
- D 编程 - 元组
- D 编程 - 结构体
- D 编程 - 共用体
- D 编程 - 范围
- D 编程 - 别名
- D 编程 - Mixin
- D 编程 - 模块
- D 编程 - 模板
- D 编程 - 不可变对象
- D 编程 - 文件 I/O
- D 编程 - 并发
- D 编程 - 异常处理
- D 编程 - 合约
- D - 条件编译
- D 编程 - 面向对象
- D 编程 - 类与对象
- D 编程 - 继承
- D 编程 - 重载
- D 编程 - 封装
- D 编程 - 接口
- D 编程 - 抽象类
- D 编程 - 有用资源
- D 编程 - 快速指南
- D 编程 - 有用资源
- D 编程 - 讨论
D 编程 - 继承
面向对象编程中最重要的概念之一是继承。继承允许根据另一个类来定义类,这使得创建和维护应用程序更容易。这也提供了重用代码功能和加快实现时间的机会。
创建类时,程序员无需编写全新的数据成员和成员函数,而是可以指定新类应该继承现有类的成员。这个现有类称为**基类**,新类称为**派生类**。
继承的概念实现了“是-a”关系。例如,哺乳动物是动物,狗是哺乳动物,因此狗也是动物,以此类推。
D 语言中的基类和派生类
一个类可以从多个类派生,这意味着它可以继承多个基类的数据和函数。要定义派生类,我们使用类派生列表来指定基类。类派生列表命名一个或多个基类,其形式为:
class derived-class: base-class
考虑一个基类**Shape**及其派生类**Rectangle**,如下所示:
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
访问控制和继承
派生类可以访问其基类所有非私有成员。因此,基类成员如果不需要被派生类的成员函数访问,应该在基类中声明为私有。
派生类继承所有基类方法,但以下情况除外:
- 基类的构造函数、析构函数和复制构造函数。
- 基类的重载运算符。
多层继承
继承可以有多个层次,以下示例展示了这一点。
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
广告