重读C#高级编程之运算符重载
我们经常进行的算术运算,比较运算实际上都是执行的一个重载运算符;但是他们只对应常见数据类型。而如果我们要对class,struct进行运算,会是什么结果哪?编译器不知道,只能有我们来重载这个操作.
Demo:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConstructorDemo
{
//二元运算符的参数之一必须是包含类型
//参数有一个必须是所在类
//-======================================================
class ReloadALG
{
static void Main(string[] args)
{
clsA cls1 = new clsA(10,50);
clsB cls2 = new clsB(50,70);
clsA result = cls1 + cls2;
Console.WriteLine(result.Inuma);
Console.WriteLine(result.Jnuma);
}
}
class clsA
{
private int inuma;
public int Inuma
{
get { return inuma; }
set { inuma = value; }
}
private int jnuma;
public int Jnuma
{
get { return jnuma; }
set { jnuma = value; }
}
public clsA(int i,int j)
{
this.inuma = i;
this.Jnuma = j;
}
}
class clsB
{
private int inumb;
public int Inumb
{
get { return inumb; }
set { inumb = value; }
}
private int jnumb;
public int Jnumb
{
get { return jnumb; }
set { jnumb = value; }
}
public clsB(int i,int j)
{
this.inumb = i;
this.jnumb = j;
}
//format: public static [returnType] operator [operator](XX,yy)
public static clsA operator +(clsA clsa, clsB clsb) //参数有一个必须是所在类
{
clsA clsresult = new clsA(0, 0);
clsresult.Inuma = clsa.Inuma + clsb.Inumb;
clsresult.Jnuma = clsa.Jnuma + clsb.Jnumb;
return clsresult;
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConstructorDemo
{
//二元运算符的参数之一必须是包含类型
//参数有一个必须是所在类
//-======================================================
class ReloadALG
{
static void Main(string[] args)
{
clsA cls1 = new clsA(10,50);
clsB cls2 = new clsB(50,70);
clsA result = cls1 + cls2;
Console.WriteLine(result.Inuma);
Console.WriteLine(result.Jnuma);
}
}
class clsA
{
private int inuma;
public int Inuma
{
get { return inuma; }
set { inuma = value; }
}
private int jnuma;
public int Jnuma
{
get { return jnuma; }
set { jnuma = value; }
}
public clsA(int i,int j)
{
this.inuma = i;
this.Jnuma = j;
}
}
class clsB
{
private int inumb;
public int Inumb
{
get { return inumb; }
set { inumb = value; }
}
private int jnumb;
public int Jnumb
{
get { return jnumb; }
set { jnumb = value; }
}
public clsB(int i,int j)
{
this.inumb = i;
this.jnumb = j;
}
//format: public static [returnType] operator [operator](XX,yy)
public static clsA operator +(clsA clsa, clsB clsb) //参数有一个必须是所在类
{
clsA clsresult = new clsA(0, 0);
clsresult.Inuma = clsa.Inuma + clsb.Inumb;
clsresult.Jnuma = clsa.Jnuma + clsb.Jnumb;
return clsresult;
}
}
}
此外
1,在对比较运算符号进行重载时,要求成对重载(==, !=)(>,<)(>=,<=)
2.比较运算符必须返回bool类型的值.