运算符重载就是重新定义运算符的功能。在你自定义的类中,运用运算符来达到自己想要的运算功能,例如二元运算符重载,就是针对两个操作数进行运算。
运算符的声明:
声明重载的方法一般用public static retype operator op(p_type)
其中,如果是一元运算符,则括号中的p_type与retype 是同一种类型,
但是,如果是二元运算,假如是 public static retype operator op(p_type , int a)
是二个参数的话,其中,第二个参数一般可以是其他类型。并且operator关键字是用来定义所要重载的运算符。
例如:下面的例子就是包含了一元与二元运算符的重载,但是,类型是相同的
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02
{
class Student
{
int num1;
int num2;
public int total;
public void GetMulti(int num1,int num2)
{
this.num1 = num1;
this.num2 = num2;
total = num2 * num1;
}
private void mytotal()
{
total += 10 ;
}
public static Student operator ++(Student s)
{
Student mys = new Student();
mys.total= s.total;
mys.mytotal();
return mys;
}
private void add()
{
}
public static Student operator +(Student s1, Student s2)
{
Student fir = new Student();
fir.total = s1.total + s2.total;
return fir;
}
public static Student operator -(Student s1, Student s2)
{
Student fir = new Student();
fir.total = s1.total - s2.total;
return fir;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.GetMulti(20,50);
Console.WriteLine(s.total);
s++;
Console.WriteLine(s.total);
Student s1 = new Student();
s1.GetMulti(20,20);
Console.WriteLine(s1 .total );
Student s2 = new Student();
s2.GetMulti(30, 30);
Console.WriteLine(s2.total);
Student sum = new Student();
sum = s1 + s2;
Console.WriteLine(sum.total);
Student sub = new Student();
sub = s1 - s2;
Console.WriteLine(sub.total);
Console.ReadKey();
}
}
}
下面的例子是不同类型的运算,这样的目的是让运算符具备了不同类型操作数的运算能力。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _01
{
class Program
{
static void Main(string[] args)
{
int com;
Company c = new Company();
Company csum = new Company();
Company csub = new Company();
com = 20;
Console.WriteLine(c.total);
csum = csum + com;
Console.WriteLine(csum.total);
csub = csub - com;
Console.WriteLine(csub.total);
Console.ReadKey();
}
}
class Company
{
public int total;
public Company()
{
total = 30;
}
public static Company operator +(Company c, int num)
{
Company myc = new Company();
myc = c;
myc.total = c.total + num;
return myc;
}
public static Company operator -(Company c, int sub)
{
Company myc = new Company();
myc = c;
myc.total = c.total - sub;
return myc;
}
}
}