overloaded operator + takes two fractions : Operator Overloading « Class Interface « C# / C Sharp

overloaded operator + takes two fractions /*
Learning C#
by Jesse Liberty

Publisher: O'Reilly
ISBN: 0596003765
*/
using System;

class Fraction
{
private int numerator;
private int denominator;

// create a fraction by passing in the numerator
// and denominator
public Fraction(int numerator, int denominator)
{
this.numerator=numerator;
this.denominator=denominator;
}

// overloaded operator + takes two fractions
// and returns their sum
public static Fraction operator+(Fraction lhs, Fraction rhs)
{
// like fractions (shared denominator) can be added
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator+rhs.numerator,
lhs.denominator);
}

// simplistic solution for unlike fractions
// 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
// this method does not reduce.
int firstProduct = lhs.numerator * rhs.denominator;
int secondProduct = rhs.numerator * lhs.denominator;
return new Fraction(
firstProduct + secondProduct,
lhs.denominator * rhs.denominator
);
}

// return a string representation of the fraction
public override string ToString()
{
String s = numerator.ToString() + "/" +
denominator.ToString();
return s;
}
}

public class TesterOverrideToString
{
static void Main()
{
Fraction f1 = new Fraction(3,4);
Console.WriteLine("f1: {0}", f1.ToString());

Fraction f2 = new Fraction(2,4);
Console.WriteLine("f2: {0}", f2.ToString());

Fraction f3 = f1 + f2;
Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString());
}
}

Related examples in the same category

 1 An example of operator overloading 2 More operator overloading 3 Overload addition for object + object, and for object + int 4 Overload the + for object + object, object + int, and int + object 5 Overload shift operator 6 Overload true and fase for ThreeD 7 A better way to overload !, | and & for ThreeD. This version automatically enables the && and || operators 8 illustrates operator overloading 9 Demonstrates overloading the addition operator for two class objects 10 Overloaded operator: whether two Fractions are equal 11 Overload != operator 12 Operator Overloading:An Example 13 Sorting and Searching:Overloading Relational Operators 