How to implement the + (plus) operator overloading in struct with C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    public struct Complex
    {
        public int x;
        public int y;

        public Complex(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        // operator overload (+)
        public static Complex operator +(Complex com1, Complex com2)
        {
            return new Complex(com1.x + com2.x, com1.y + com2.y);
        }

        public override string ToString()
        {
            return (String.Format("{0} + {1}", x, y));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Complex complex1 = new Complex(13, 19);
            Complex complex2 = new Complex(1, 2);

            Complex sum_complex = complex1 + complex2;

            Console.WriteLine("complex1 = {0}", complex1);
            Console.WriteLine("complex2 = {0}", complex2);

            Console.WriteLine("sum_complex = {0}", sum_complex);
        }
    }
}



/*
run:

complex1 = 13 + 19
complex2 = 1 + 2
sum_complex = 14 + 21

*/

 



answered Apr 27, 2017 by avibootz

Related questions

2 answers 245 views
1 answer 241 views
1 answer 216 views
2 answers 272 views
1 answer 249 views
249 views asked Sep 6, 2015 by avibootz
1 answer 163 views
1 answer 222 views
...