参考书:《 visual C# 从入门到精通》
第三部分 用C#定义可扩展类型
第22章 操作符重载
22.1 理解操作符
22.1.1 操作符的限制
需要用到关键字operator
:
struct Hour{
public Hour(int initialValue){
this.value=initialValue;
}
public static Hour operator +(Hour lhs,Hour rhs){
return new Hour(lhs.value+rhs.value);
}
...;
private int value;
}
注意:
- 所有操作符必须时公共的、静态的,不具有多态性,不能用修饰符
virtual
、abstruct
、override
或sealed
- 二元操作符有两个现实的参数,一元操作符有一个显式的参数
22.1.3 创建对称操作符
22.2 理解复合操作符
22.3 声明递增和递减操作符
struct Hour{
...;
public static Hour operator ++(Hour arg){
arg.value++;
return arg;
}
...;
}
注意区分前缀版本和后缀版本。
22.4 比较结果和类中的操作符
前面的Hour
是结构,如果是类的话递增操作符的正确实现应该如下:
class Hour{
public Hour(int initialValue){
this.value=initialValue;
}
...;
public static Hour operator ++(Hour arg){
return new Hour(arg.value+1);
}
...;
private int value;
}
22.5 定义成对的操作符
有的操作符是需要成对使用的,如==
和!=
,>
和<
,<=
和>=
。所有操作符都要自己去适当的定义。
22.6 实现操作符
下面我们来创建一个类来实现复数的计算。(.NET Framework中自带了Complex
类型,在System.Numerics
中,所以真正要实现复数的话没必要自己特意去定义。)
我们可以将Complex
类自己定义如下:
Complex.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace c_22_6
{
class Complex
{
public double Real { get; set; }
public double Imag { get; set; }
public Complex(double r,double i)
{
this.Real = r;
this.Imag = i;
}
public override string ToString()
{
return $"({this.Real} +{this.Imag}i)";
}
public static Complex operator +(Complex l,Complex r)
{
return new Complex(l.Real + r.Real, l.Imag + r.Imag);
}
public static Complex operator -(Complex l,Complex r)
{
return new Complex(l.Real - r.Real, l.Imag - r.Imag);
}
public static Complex operator *(Complex l,Complex r)
{
return new Complex(l.Real * r.Real - l.Imag * r.Imag,
l.Real * r.Imag + l.Imag * r.Real);
}
public static Complex conj(Complex arg)//共轭
{
return new Complex(arg.Real, -arg.Imag);
}
public static Complex operator /(Complex l,int r)
{
return new Complex(l.Real / r, l.Imag / r);
}
public static double abs2(Complex arg)
{
Complex c = arg * conj(arg);
return c.Real;
}
public static Complex operator /(Complex l,Complex r)
{
Complex c = l * conj(r);
return new Complex(c.Real / abs2(r), c.Imag / abs2(r));
}
}
}
在Program.cs
中验证我们创建的这个类:
using System;
namespace c_22_6
{
class Program
{
static void dowork()
{
Complex f = new Complex(10, 4);
Complex s = new Complex(5, 2);
Console.WriteLine($"first is {f}");
Console.WriteLine($"second is {s}");
Console.WriteLine($"Add: result is {f + s}");
Console.WriteLine($"Substract: result is {f - s}");
Console.WriteLine($"Multiply: result is {f * s}");
Console.WriteLine($"Divide: result is {f / s}");
}
static void Main(string[] args)
{
dowork();
}
}
}
运行结果:
first is (10 +4i)
second is (5 +2i)
Add: result is (15 +6i)
Substract: result is (5 +2i)
Multiply: result is (42 +40i)
Divide: result is (2 +0i)
C:\Users\xhh\Source\Repos\c_22_6\c_22_6\bin\Debug\netcoreapp3.1\c_22_6.exe (进程 29004)已退出,代码为 0。
按任意键关闭此窗口. . .