Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize operator overloading in C #

Shulou Source: shulou.com Published: 2022-06-01 01:52:37 09月29日 Update

This article introduces the relevant knowledge of "how to realize operator overloading in C#". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Implementation of operator overloading

The following program demonstrates the complete implementation:

Using System

Namespace OperatorOvlApplication

{

Class Box

{

Private double length; / / length

Private double breadth; / / width

Private double height; / / 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

}

/ / overload + operator to add two Box objects

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 (); / / declare Box1 with type Box

Box Box2 = new Box (); / / declare Box2 with type Box

Box Box3 = new Box (); / / declare Box3 with type Box

Double volume = 0; / / Volume

/ / Box1 details

Box1.setLength (6.0)

Box1.setBreadth (7. 0)

Box1.setHeight (5.0)

/ / Box2 details

Box2.setLength (12.0)

Box2.setBreadth (13.0)

Box2.setHeight (10.0)

/ / Volume of Box1

Volume = Box1.getVolume ()

Console.WriteLine ("volume of Box1: {0}", volume)

/ / Volume of Box2

Volume = Box2.getVolume ()

Console.WriteLine ("volume of Box2: {0}", volume)

/ / add two objects together

Box3 = Box1 + Box2

/ / Volume of Box3

Volume = Box3.getVolume ()

Console.WriteLine ("volume of Box3: {0}", volume)

Console.ReadKey ()

}

}

}

When the above code is compiled and executed, it produces the following results:

The volume of Box1: the volume of 210Box2: the volume of 1560Box3: 5400 "how to realize operator overloading in C#" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Volume operator operation type Category two content object more knowledge faceted practical successful next code dilemma actual width situation article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Xiaomi MySQL MariaDB Apple