using System;
namespace _6_2_1运算符重载
{
class Program
{
static void Main(string[] args)
{
Student st1 = new Student();
Student st2 = new Student();
Student st3 = new Student();
st1._acore = 40;
st2._acore = 50;
Console.WriteLine("st1和st2成绩是否相同:" + (st1 == st2));
Console.WriteLine("st1和st2成绩是否相同:" + (st1 != st2));
Console.WriteLine("运算前成绩:{0},{1},{2}", st1._acore, st2._acore, st3._acore);
//对象相加
st3 = st1 + st2;
//编译器自动重载+=
st1 += st2;
Console.WriteLine("运算后成绩:{0},{1},{2}",st1._acore,st2._acore,st3._acore);
Console.ReadKey();
}
}
class Student
{
private int acore;
public int _acore {
get { return acore; }
set { acore = value; }
}
//+重载: 对象加法,求得学生成绩和
public static Student operator +(Student b, Student c)
{
Student stu = new Student();
stu.acore = b.acore + c.acore;
return stu;
}
//当重载==时,必须重载!=,否则编译报错
public static bool operator ==(Student b , Student c)
{
bool result = false;
if(b.acore == c.acore)
{
result = true;
}
return result;
}
public static bool operator !=(Student b, Student c)
{
bool result = false;
if (b.acore != c.acore)
{
result = true;
}
return result;
}
}
}
评论