Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

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

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    public class 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(11, 15);
            Complex complex2 = new Complex(3, 4);

            Complex sum_complex = complex1 + complex2;

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

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



/*
run:

complex1 = 11 + 15
complex2 = 3 + 4
sum_complex = 14 + 19

*/

 



answered Apr 27, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication1
{
    class Test
    {
        public int _n;

        public static Test operator + (Test x, Test y)
        {
            Test t = new Test();

            t._n = x._n + y._n;

            return t;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test a = new Test();
            a._n = 3;

            Test b = new Test();
            b._n = 10;

            Test t = a + b;
            Console.WriteLine(t._n);
        }
    }
}

/*
run:
  
13
     
*/

 



answered Apr 27, 2017 by avibootz

Related questions

1 answer 190 views
1 answer 210 views
1 answer 205 views
2 answers 255 views
1 answer 237 views
237 views asked Sep 6, 2015 by avibootz
1 answer 149 views
1 answer 134 views
134 views asked Dec 2, 2022 by avibootz
...