C#

C# polymorphism (1/4) - Overloading

Choi G.H 2019. 6. 5. 19:51
반응형

메서드 오버로딩

 

메서드의 이름은 같지만 아규먼트의 개수나 타입 도는 ref, out, params와 같은 키워드의 유무에 따라 다른 메서드가 생기는데, 이것을 오버로딩(Oberloading)이라 한다.

 

 

        public static void Clear(int[] m)                        //기존 메서드
          {
            Array.Clear();
          }

        public static void Clear(int[] m, int n)      //오버로딩된 메서드
          {
            for (int i = 0; i < m.Length; i++)
                m[i] = n; 
          }

 

생성자 오버로딩

 

 class Program
    {
        static void Main()
        {
            Z z1 = new Z(3.0, -2);
            Console.WriteLine(z1);
            z2 = new Z(4, 5);
            Console.WriteLine(z2);
            z3 = new Z();
            Console.WriteLine(z3);
        }

    }

    public class Z
    {
        private double x;
        private double y;

        public Z(double x, double y)
        {
            this.x = x;
            this.y = y;
        }

        public Z() : this(0.0, 0.0) { }              //생성자를 이용해 멤버를 초기화하는 오버로딩 생성자.

        public override string ToString()
        {
            if (y < 0)
            {
                return string.Format("({0}-{1}i)", x, Math.Abs(y));
            }
            else
            {
                return string.Format("({0}+{1}i)", x, y);
            }
        }

 

 

반응형