重载是在一个类定义中,可以编写几个同名的方法,但是只要它们的签名参数列表不同,J就会将它们看做唯一的方法;重载可使函数、运算符等处理
不同类型数据或接受不同个数的参数的一种方法;它发生在同一个类中。
例如:- class MainClass
- {
- struct Vector
- {
- public double x, y, z;
- public Vector(double x, double y, double z)
- {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- public Vector(Vector rhs)
- {
- x = rhs.x;
- y = rhs.y;
- z = rhs.z;
- }
- public override string ToString()
- {
- return "(" + x + "," + y + "," + z + ")";
- }
- public static Vector operator +(Vector lhs, Vector rhs)
- {
- Vector result = new Vector(lhs);
- result.x += rhs.x;
- result.y += rhs.y;
- result.z += rhs.z;
- return result;
- }
- }
- static void Main()
- {
- Vector vect1, vect2, vect3;
- vect1 = new Vector(3.0, 3.0, 1.0);
- vect2 = new Vector(2.0, -4.0, -4.0);
- vect3 = vect1 + vect2;
- Console.WriteLine("vect1=" + vect1.ToString());
- Console.WriteLine("vect2=" + vect2.ToString());
- Console.WriteLine("vect3=" + vect3.ToString());
- }
- }
- 上例定义了一个在数学中常见的矢量相加的+号重载
复制代码 至于复写我还不太懂,就暂时不班门弄斧了,等我学通了再来告诉你吧!
|