跳到主要内容

SCL 运算符重载

本页说明自定义类型需要用 +、比较或位运算表达工程量时如何声明运算符。SCL 支持类上的二元运算符重载。一元运算符、转换运算符和表达式体运算符当前不可用。

基本语法​

运算符声明使用块体、两个参数和明确返回类型。左操作数应是声明该运算符的类。

class Level
{
public int Value;

public static Level operator +(Level left, Level right)
{
Level total = new Level();
total.Value = left.Value + right.Value;
return total;
}
}

Level first = new Level();
first.Value = 10;
Level second = new Level();
second.Value = 5;
Level total = first + second;

可重载的二元运算符​

运算符方法签名说明
a + bpublic static T operator +(T a, T b)加法
a - bpublic static T operator -(T a, T b)减法
a * bpublic static T operator *(T a, T b)乘法
a / bpublic static T operator /(T a, T b)除法
a % bpublic static T operator %(T a, T b)取模
a & bpublic static T operator &(T a, T b)按位与
按位或两个同类操作数,源码写竖线运算符按位或
a ^ bpublic static T operator ^(T a, T b)按位异或
a == b / a != bpublic static bool operator ==(T a, T b)相等 / 不等
a < b / a > bpublic static bool operator <(T a, T b)小于 / 大于
a <= b / a >= bpublic static bool operator <=(T a, T b)小于等于 / 大于等于

比较运算符按声明逐个解析。编译器不会自动生成缺少的相反运算符。

混合类型右操作数​

右操作数可以是标量,左操作数仍应是声明运算符的类:

class Current
{
public double Amps;

public static Current operator *(Current current, double factor)
{
Current scaled = new Current();
scaled.Amps = current.Amps * factor;
return scaled;
}
}

Current input = new Current();
input.Amps = 5.0;
Current doubled = input * 2.0;

不要声明把外部标量放在左侧的反向重载。

当前边界​

  • 运算符进入正常的方法调用路径,不创建线程。
  • 高频扫描代码仍应评估执行成本,不要因写法简短就假设没有开销。
  • + 表示合并或累加,不要用运算符实现反直觉语义。

当前不可用​

  • 一元 + / - / ! / ~、++、--、true / false。
  • 移位运算符重载。
  • implicit / explicit 转换运算符。
  • 表达式体 =>。
  • 源码 struct 上的运算符。