Create a class Int based on Q 1 . Overload four integer arithmetic operators (+, -, *, and /) so that they operate on objects of type Int. If the result of any such arithmetic operation exceeds the normal range of ints
static void Main(string[] args)
{
//Example of program usage
Int a = new Int(10);
Int b = new Int(5);
Int res = a + b; // 10 + 5 = 15
Console.WriteLine(res);
res = a - b; // 10 - 5 = 5
Console.WriteLine(res);
res = a / b; // 10 / 5 = 2
Console.WriteLine(res);
res = a * b; // 10 * 5 = 50
Console.WriteLine(res);
Console.ReadKey();
}
}
class Int
{
private int value; // Variable for value
public int Value => value; // Property that returns value
public Int() // Default constructor
{
value = 0;
}
public Int(int value) // Constructor with parameter
{
this.value = value;
}
// Operators overloading
public static Int operator +(Int a, Int b)
{
return new Int(a.Value + b.Value);
}
public static Int operator -(Int a, Int b)
{
return new Int(a.Value - b.Value);
}
public static Int operator *(Int a, Int b)
{
return new Int(a.Value * b.Value);
}
public static Int operator /(Int a, Int b)
{
return new Int(a.Value / b.Value);
}
public override string ToString()
{
return Value.ToString();
}
Comments
Leave a comment