创建控制台应用程序,重载二元运算符+-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DuoTai2
{
class Program
{
static void Main(string[] args)
{
one test1 = new one(1,2);
one test2 = new one(3, 4);
Console.WriteLine((test1+test2).ToString());
Console.WriteLine((test2-test1).ToString());
Console.ReadKey();
}
}
public struct one
{
private int x;
private int y;
public one (int x,int y)//构造函数初始化对象
{
this.x = x;
this.y = y;
}
public override string ToString()//重写Tostring
{
return string.Format("坐标{0},{1}",x,y); //字符串格式化函数使用很简单.如 string a=string.Format("你的姓名:{0},年龄:{1}","张三",16);得到的a 就是 "你的姓名:张三,年龄16", 这个函数主要避免 字符串多次 拼凑相加 造成错误或者麻烦.这个 函数有一个 格式参数,和若干个 parameters 参数. 还有 参数是从0开始的.
}
public static one operator+(one p1,one p2)//重载运算符
{
return new one(p1.x + p2.x, p1.y + p2.y);
}
public static one operator -(one p1, one p2)//重载运算符
{
return new one(p1.x - p2.x, p1.y - p2.y);
}
}
}