什么是运算符重载?
重载是面向对象中的一个重载概念,它是对象多态性的一种不完全体现。所谓运算符重载,就是对已有的运算符重新定义,赋予其另一种功能,以适应不同的数据类型。
为什么要需要运算符重载?
比如:
1+1=2 这是系统默认可以识别并可以运算的
1杯水+1杯水=2杯水 这时系统就无法判断你要做什么。
此时就需要重新定义“+”运算符就可以实现生活中各种对象之间“和”的运算。
运算符重载格式
访问修饰权限 +数据类型+关键字(operator)+运算符+(形参表)
{
函数体 ;
}
运算符重载实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class Program
{
public static void Main(string[] args)
{
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.ToString());
Console.WriteLine(vect2.ToString());
Console.WriteLine( vect3.ToString());
}
class Vector
{
private double x, y, z;
public double X
{
get { return x; }
set { y = value; }
}
public double Y
{
get { return y; }
set { y = value; }
}
public double Z
{
get { return z; }
set { z = value; }
}
public Vector()
{
x = 0;
y = 0;
z = 0;
}
public Vector(Vector rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
}
public Vector(double x, double y, double z)
{
this .x=x ;
this .y=y;
this.z=z;
}
public override string ToString()
{
return "X的坐标是:"+x+"Y的坐标是:"+y+"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;
}
}
}
}
运行的结果如下
不同的运算符中重载时有不同的要求