1.运算符重载与理解
重载定义:运算符重载是将“+”、“-”、“--------”等运算符看作方法,在类中重新定义方法功能
理解:简写代码如下
int a = 10;
int b= 20;
int c = a + b;
int +(int m,int n) //将+当作方法,方法实现功能与c一致
{
return m + n; //+方法返回值为两束相加
}
格式:
//双目运算符
public static 返回类型 operator 符号 (类型 对象1,类型 对象2)
//单目运算符 ++、–
public static 返回类型 operator 符号 (类型 对象)
2.案列
1.双目运算符:两个数据集相加或两个数据集相减
class box
{
public int width = 0;
public int height = 0;
public int detph = 0;
//重载+运算符
public static box operator +(box left, box right)
{
box box = new box();
box.width = left.width + right.width;
box.height = left.height + right.height;
box.detph = left.detph + right.detph;
return box;
}
//重载-运算符
public static box operator -(box left, box right)
{
box box = new box();
box.width = left.width - right.width;
box.height = left.height - right.height;
box.detph = left.detph - right.detph;
return box;
}
}
static void Main(string[] args)
{
box b0=new box();
box b1=new box();
b0.width = 10;
b0.height = 10;
b0.detph = 10;
b1.width = 20;
b1.height = 20;
b1.detph = 20;
box b = b0 + b1; //+是一种方法,不是运算符
//box b=box.operator+(b0, b1); //等效于上一条语句
Console.WriteLine(b.width);
Console.WriteLine(b.height);
Console.WriteLine(b.detph);
Console.ReadLine();
}
}
2.单目运算符:
一个数据集内部参数做运算,单目运算符取反
internal class Program
{
class Vector2
{
public int x=0;
public int y=0;
public static Vector2 operator-(Vector2 V1) //传入Vector2 类型的V1对象
{
Vector2 v = new Vector2();
v.x = -V1.x; //v对象的X取传入V1对象的X取反操作
v.y = -V1.y;
return v;
}
}
static void Main(string[] args)
{
Vector2 v = new Vector2();
v.x = 10;
v.y = 20;
Vector2 nv = -v;
Console.WriteLine(nv.x);
Console.WriteLine(nv.y);
Console.ReadLine();
}
}
3.单目运算符:++/——,自增自减运算
//单目运算符中的++、——
//a++:后缀++,先参与表达式运算,再+1
//++a:前缀++,先自身+1,再参与表达式运算
//a++与++a调用的是同一个函数,C#中不做区分
public static Vector2 operator ++(Vector2 v)
{
v.x +=1;
v.y +=1;
return v;
}
//main中函数部分
Vector2 vector = new Vector2();
vector.x = 10;
vector.y = 20;
Vector2 vector2 = vector++;
Console.WriteLine(vector2.x);
Console.WriteLine(vector2.y);
Console.ReadLine();