C# 運算子實現類別多載 - 教學筆記 (使用visual studio)
Operator Overloading on Class
在C#設計Class,可以搭配運算子(operator)來做到多載(overloading) 並且,要Overloading的運算子,必須是 static 例如:
class Box
{
public int Height { get; set; }
public int Width { get; set; }
public Box(int h, int w)
{
Height = h;
Width = w;
}
public static Box operator +(Box a, Box b)
{
int h = a.Height + b.Height;
int w = a.Width + b.Width;
Box res = new Box(h, w);
return res;
}
}
static void Main(string[] args)
{
Box b1 = new Box(14, 3);
Box b2 = new Box(5, 7);
Box b3 = b1 + b2;
Console.WriteLine(b3.Height);
Console.WriteLine(b3.Width);
}
底下範例中,實現多載 operator +, operator -, operator *, operator /
Continue Reading