请问重载操作的作用是什么

来源:百度知道 编辑:UC知道 时间:2024/05/26 02:07:28
using System;

class Rectangle
{
private int iHeight;
private int iWidth;

// 缺省构造函数
public Rectangle()
{
Height=0;
Width=0;
}

// 构造函数重载
public Rectangle(int w,int h)
{
Width=w;
Height=h;
}

// 属性:宽 的get和set访问器
public int Width
{
get
{
return iWidth;
}
set
{
iWidth=value;
}
}

// 属性:高 的get和set访问器
public int Height
{
get
{
return iHeight;
}
set
{
iHeight=value;
}
}

// 属性:面积 的get访问器
public int Area
{
get
{
return Height*Width;
}
}

// 重载操作符 ==
public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Wi

这个程序重载操作符的作用恐怕就是为了能更简洁的进行比较
像这个:
public static bool operator>(Rectangle a,Rectangle b)
{
return a.Area>b.Area;
}

如果没有重载操作符,在比较a和b的面积时,你可能就要这么写:
if(a.Area>b.Area) Console.WriteLine("矩形1大于矩形2");

但是运算符重载之后,你只需这么写:
if(a>b) Console.WriteLine("矩形1大于矩形2");
省事不少
你再看看其它的,都有类似作用
public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Width==b.Width));
}

这个是规定用==比较a与b的时候,要求a与b的长宽都相等,才能叫作a==b

在规定好了等于(==)、大于(>),小于(<)等操作后,才因此衍生出后面的>=、<=等运算操作

重载可以实现很多功能,
根据不同需要进行不同的字段初始化 既可以节省资源
又可以使代码更简介易懂
总之好处很多
用多了自然就明白了

不用重新定义函数,只要使用不同的参数,或者使用不同的参数个数就可以自动进行匹配

对具有不同返回类型或者具有不同参数的函数进行操作,当调用时,会自动寻找最匹配的。

对具有不同返回类型或者具有不同参数的函数进行操作,当调用时,会自动寻找最匹配的。

不懂