运算符重载是OOP多态的体现之一
运算符重载
含义:对已有的运算符进行重定义,而给予其全新的功能,以适应不同的数据类型(还有很多其他用法)
熟练运用运算符重载可以写出很多 真·令人智熄 的语法糖
例子:复数加法
复数无法用+
直接运算,需要重载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Complex { public double Real { get; set; } public double Image { get; set; } public Complex( double Real, double Image ) { this.Real = Real; this.Image = Image; } public override String ToString() { return String.Format($"{Real} + i{Image}"); } public static Complex operator + ( Complex a, Complex b ) { return new Complex( a.Real + b.Real, a.Image + b.Image ); } }
|
- 运算符重载必须在需要的类中实现
- 必须是
public static
类型,是在类层次的
- 简单的理解就是:定义函数的方法中的函数名改成
operator
+需要重载的运算符
注意点
可以重载的运算符(一部分)
1 2 3 4 5
| +, -, !, ~, ++, --, true, false
+, -, *, /, %, &, |, ~, ^, <<, >>
|