企业建设网站的作用,宝安高端网站建设,专业网站制作团队专业网站制作团队,太原市网站制作公司C# 中支持运算符重载#xff0c;所谓运算符重载就是我们可以使用自定义类型来重新定义 C# 中大多数运算符的功能。运算符重载需要通过 operator 关键字后跟运算符的形式来定义的#xff0c;我们可以将被重新定义的运算符看作是具有特殊名称的函数#xff0c;与其他函数一样所谓运算符重载就是我们可以使用自定义类型来重新定义 C# 中大多数运算符的功能。运算符重载需要通过 operator 关键字后跟运算符的形式来定义的我们可以将被重新定义的运算符看作是具有特殊名称的函数与其他函数一样该函数也有返回值类型和参数列表如下例所示
public static Box operator (Box b, Box c) {Box box new Box();box.length b.length c.length;box.breadth b.breadth c.breadth;box.height b.height c.height;return box;
}重点 运算符重载格式
public static ClassName operator##op (ele) {//something
}下表描述了 C# 中运算符重载的能力
运算符 描述
运算符描述, -, !, ~, , –这些一元运算符只有一个操作数且可以被重载。, -, *, /, %这些二元运算符带有两个操作数且可以被重载。, !, , , , 这些比较运算符可以被重载。, ||这些条件逻辑运算符不能被直接重载。, -, *, /, %这些赋值运算符不能被重载。, ., ?:, -, new, is, sizeof, typeof这些运算符不能被重载。
细看
using System;//主程序入口
class TODO {static void Main() {Console.WriteLine(Hello C#!);ComplexNumber a new ComplexNumber(1, 2);ComplexNumber b new ComplexNumber(2, 5);ComplexNumber c new ComplexNumber();c a b;Console.WriteLine(c {0} {1}i,c.real, c.imaginary);double rea, imb;c.linkA(out rea).linkB(out imb);Console.WriteLine(rea {0}, imb {1}, rea, imb);}
}class ComplexNumber{//私有成员 实部和虚部private double Real;private double Imaginary;//get setpublic double real {get { return Real; } set { Real value; } }public double imaginary {get { return Imaginary; }set { Imaginary value; }}//含参构造public ComplexNumber(double re 0.0, double im 0.0) {real re;imaginary im;}~ComplexNumber() { }//运算符重载public static ComplexNumber operator (ComplexNumber a, ComplexNumber b) {ComplexNumber c new ComplexNumber(0, 0);c.real a.real b.real;c.imaginary a.imaginary b.imaginary;return c;}//链式调用public ComplexNumber linkA(out double re) {re real;return this;}public ComplexNumber linkB(out double im) {im imaginary;return this;}}