- 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 编程 - 讨论
一元运算符重载
下表显示了一元运算符及其用途列表。
| 函数名 | 运算符 | 用途 |
|---|---|---|
| opUnary | - | 负数(数值补码) |
| opUnary | + | 相同的值(或副本) |
| opUnary | ~ | 按位取反 |
| opUnary | * | 访问其指向的内容 |
| opUnary | ++ | 递增 |
| opUnary | -- | 递减 |
以下示例说明如何重载二元运算符。
import std.stdio;
class Box {
public:
double getVolume() {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
Box opUnary(string op)() {
if(op == "++") {
Box box = new Box();
box.length = this.length + 1;
box.breadth = this.breadth + 1 ;
box.height = this.height + 1;
return box;
}
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
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);
// volume of box 1
volume = Box1.getVolume();
writeln("Volume of Box1 : ", volume);
// Add two object as follows:
Box2 = ++Box1;
// volume of box2
volume = Box2.getVolume();
writeln("Volume of Box2 : ", volume);
}
编译并运行上述代码后,将产生以下结果:
Volume of Box1 : 210 Volume of Box2 : 336
d_programming_overloading.htm
广告