c#运算符重载

(就是使自己写的类可以实现运算)

可以重定义或重载 C# 中内置的运算符。因此,可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。

csharp 复制代码
namespace OperatorOvlApplication
{
   class Box
   {
      private double length;      // 长度
      private double breadth;     // 宽度
      private double height;      // 高度
      public double getVolume()
      {
         return length * breadth * height;
      }
      public void setLength( double len )
      {
         length = len;
      }
      public void setBreadth( double bre )
      {
         breadth = bre;
      }
      public void setHeight( double hei )
      {
         height = hei;
      }
      //定义重载!!!!!!!!!!
      // 重载 + 运算符来把两个 Box 对象相加
      public static Box operator+ (Box b, Box c)//实现了自定义类的"+"运算
      {
         Box box = new Box();
         box.length = b.length + c.length;
         box.breadth = b.breadth + c.breadth;
         box.height = b.height + c.height;
         return box;
      }
   }
   class Tester
   {
      static void Main(string[] args)
      {
         Box Box1 = new Box();         // 声明 Box1,类型为 Box
         Box Box2 = new Box();         // 声明 Box2,类型为 Box
         Box Box3 = new Box();         // 声明 Box3,类型为 Box
         double volume = 0.0;          // 体积
         // Box1 详述
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);
         // Box2 详述
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);
         // 把两个对象相加
         Box3 = Box1 + Box2;//使用了重载函数!!!!!!!!!!
         // Box3 的体积
         volume = Box3.getVolume();
         Console.WriteLine("Box3 的体积: {0}", volume);
         Console.ReadKey();
      }
   }
}
相关推荐
阿猿收手吧!6 分钟前
【C++】string_view:高效字符串处理指南
开发语言·c++
玄同76536 分钟前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang1 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl13071 小时前
C++算法(1)双指针
开发语言·c++
不绝1911 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
无小道1 小时前
Qt-qrc机制简单介绍
开发语言·qt
zhooyu1 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷1 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
大鹏说大话1 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
Mr_sun.2 小时前
Day09——入退管理-入住-2
android·java·开发语言