- D 编程基础
- D 编程 - 主页
- D 编程 - 概述
- D 编程 - 环境
- D 编程 - 基本语法
- D 编程 - 变量
- D 编程 - 数据类型
- D 编程 - 枚举
- D 编程 - 文字
- D 编程 - 运算符
- D 编程 - 循环
- D 编程 - 决策
- D 编程 - 函数
- D 编程 - 字符
- D 编程 - 字符串
- D 编程 - 数组
- D 编程 - 关联数组
- D 编程 - 指针
- D 编程 - 元组
- D 编程 - 结构
- D 编程 - 联合
- D 编程 - 范围
- D 编程 - 别名
- D 编程 - Mixins
- D 编程 - 模块
- D 编程 - 模板
- D 编程 - 不可变
- D 编程 - 文件 I/O
- D 编程 - 并发
- D 编程 - 异常处理
- D 编程 - 合同
- D - 条件编译
- D 编程 - 面向对象
- D 编程 - 类和对象
- D 编程 - 继承
- D 编程 - 重载
- D 编程 - 封装
- D 编程 - 接口
- D 编程 - 抽象类
- D 编程 - 有用的资源
- D 编程 - 快速指南
- D 编程 - 有用的资源
- D 编程 - 讨论
D 编程 - 类成员函数
成员函数是特定于类的函数。它对它所属的类的任何对象进行操作,并且可以访问该对象的类的所有成员。
在对象上使用点运算符 ( . ) 来调用成员函数,在该对象上操作与该对象相关的数据。
让我们将上述概念来设置和获取类中不同类成员的值 -
import std.stdio;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume() {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
}
void main( ) {
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
writeln("Volume of Box1 : ",volume);
// volume of box 2
volume = Box2.getVolume();
writeln("Volume of Box2 : ", volume);
}
当上面的代码被编译并执行时,它会产生以下结果 -
Volume of Box1 : 210 Volume of Box2 : 1560
d_programming_classes_objects.htm