fork download
  1. using System;
  2.  
  3. public struct Complex
  4. {
  5. public int real;
  6. public int imaginary;
  7.  
  8. public Complex(int real, int imaginary)
  9. {
  10. this.real = real;
  11. this.imaginary = imaginary;
  12. }
  13.  
  14. // Declare which operator to overload (+), the types
  15. // that can be added (two Complex objects), and the
  16. // return type (Complex):
  17. public static Complex operator +(Complex c1, Complex c2)
  18. {
  19. return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
  20. }
  21. // Override the ToString method to display an complex number in the suitable format:
  22. public override string ToString()
  23. {
  24. return(String.Format("{0} + {1}i", real, imaginary));
  25. }
  26.  
  27. public static void Main()
  28. {
  29. Complex num1 = new Complex(2,3);
  30. Complex num2 = new Complex(3,4);
  31.  
  32. // Add two Complex objects (num1 and num2) through the
  33. // overloaded plus operator:
  34. Complex sum = num1 + num2;
  35.  
  36. // Print the numbers and the sum using the overriden ToString method:
  37. Console.WriteLine("First complex number: {0}",num1);
  38. Console.WriteLine("Second complex number: {0}",num2);
  39. Console.WriteLine("The sum of the two numbers: {0}",sum);
  40.  
  41. }
  42. }
Success #stdin #stdout 0.03s 24152KB
stdin
Standard input is empty
stdout
First complex number:  2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i