stuart-d2
10/13/2014 - 3:51 PM

Operator Overloading -- I do not completely understand this yet. It seems on Stack|Overflow many people try to just circumvent the issue b

Operator Overloading -- I do not completely understand this yet.
It seems on Stack|Overflow many people try to just circumvent the issue by redesigning.
I've also checked existing code repo here at work -- no body has done this.
Therefore, seems this might be a very edge case for use, so the jury is still out on this.
Program compiles (linqpad-C#Program), yet I fully do not understand the complete concept yet.

//A complex struct - Complex

public struct Complex
{
	//both my fields are of datatype int.
	public int real;
	public int imaginary;
	
	//The constructor. Inputs : real int & imaginary int
	public Complex(int real, int imaginary)
	{
		//setters
		this.real = real;
		this.imaginary = imaginary;
	}
	
/*
The class where I am overloading an operator.
I am doing this because basic operators(+) would not know how
to add these two complex objects together.  
Declaring a operator to overload (+), two complex user-defined 
operands that I intend to add together and the return type (Complex)
static and public required, this is being done on a Binary operator
*/
//syn
//|required     | type  |keyword||Operator|Operand        |
   public static Complex operator +(Complex c1, Complex c2)
	{
		return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
	}

//Overriding the ToString method to display a complex number in 
// a suitable format :
public override string ToString()
	{
	return(String.Format("{0} + {1}i", real, imaginary));
	}
	
	public static void Main()
	{
	//Sending in two numbers... Though nothing really seems 
	//special here to me. Creating two 'Complex' objects with 
	//two basic numbers
	Complex num1 = new Complex(2,3);
	Complex num2 = new Complex(3,4); 
	
	//Adds the two complex objects - num1 and num2 through the 
	//overloaded plus operator.  Ok, that's a little more different --
	// adding two objects together... now '+' does something totally 
	// different, adding two objects together.
	Complex sum = num1 + num2;
	
	//Print the numbers and the sum using the overriden ToString method:
	Console.WriteLine("First complex number:  {0}", num1);
	Console.WriteLine("Second complex number:  {0}", num2);
	Console.WriteLine("The sum of the two numbers: {0}",sum);
	}
}
	//Output:
	//First complex number:  2 + 3i
	//Second complex number:  3 + 4i
	//The sum of the two numbers: 5 + 7i