封装的目的是为了代码安全
,调试容易
,当然还有方便理解
.
可在构/类
级别,或在模块
级别指定封装关系.
词 | 意思 |
---|---|
public |
本程序任意访问 |
private |
限制只能由定义 他的模块 访问.此外子类 不能覆盖基类私 成员. |
package |
包级访问,属于某包都可以访问.包属性仅包含最里边 的包.vertebrate 下的所有包都可以访问在animal.vertebrate.cat 里定义的包定义 函数(有包),子类不能覆盖包成员函数 |
protected |
继承类可访问 |
export |
外部程序都可访问,最大 |
//java式
private int foo;
private void bar() {
// ...
}
//c++式
private:
// ...
// ... 私
// ...
protected:
// ...
// ... 保护
// ...
//块式
private {
// ...
// ... 私
// ...
}
导入模块默认为私.可以加个公开
module school.school;
public import school.student;//可间接访问
//从而
import school.school;
void main() {
auto student = Student("Tim", Gender.male);
// ...
}
封装
是面向对象,最强大之处.示例:
module school.student;
import std.string;
import std.conv;
enum Gender { female, male }
struct Student {
package string name;
package Gender gender;
string toString() const {
return format("%s 是%s 学生.",
name, to!string(gender));
}
}
module school.school;
public import school.student; // 1
import std.string;
class School {
private: // 2
Student[] students;
size_t femaleCount;
size_t maleCount;
public: // 3
void add(in Student student) {
students ~= student;
final switch (student.gender) { // 4a
case Gender.female:
++femaleCount;
break;
case Gender.male:
++maleCount;
break;
}
}
override string toString() const {//盖,继承自`object`
string result = format(
"%s 女, %s 男; 总共 %s 学生",
femaleCount, maleCount, students.length);
foreach (i, student; students) {
result ~= (i == 0) ? ": " : ", ";
result ~= student.name; // 4b
}
return result;
}
}
import std.stdio;
import school.school;
void main() {
auto student = Student("Tim", Gender.male);
writeln(student);
auto school = new School;
school.add(Student("Lindsey", Gender.female));
school.add(Student("Mark", Gender.male));
school.add(Student("Nancy", Gender.female));
writeln(school);
}