c#允许重载运算符,使你自己定义的数据类型可以象基本数据类型那样进行运算,方便.
如果为ComplexNumber重载运算符+ 可以这样定义
public static ComplexNumber opertor+(ComplexNumber a,ComplexNumber b)
{
}
所有运算符重载均为类的静态方法.并且==与!=,<与>,<=和>=必须成对重载.
示例:
public class ComplexNumber
{
int real;
int imaginary;
public ComplexNumber():this(0,0)
{
}
public ComplexNumber(int r,int i)
{
real = r;
imaginary = i;
}
public override string ToString()
{
return (System.String.Format("{0}+{1}i",real,imaginary));
}
public static ComplexNumber operator+(ComplexNumber a,ComplexNumber b)
{
return new ComplexNumber(a.real+b.real,a.imaginary+b.imaginary);
}
}
class test
{
static void Main()
{
ComplexNumber a = new ComplexNumber(4, 6);
ComplexNumber b = new ComplexNumber(2, 6);
System.Console.WriteLine((a+b).ToString());
}
}
输出:
6+12i
请按任意键继续. . .