<오버로딩과 오버라이드>메서드 오버라이드(상속)이해못함 내일 다시할 것

C#/과제 2019. 3. 26. 00:13

c# override, overload

다형성



overloading

메서드의 이름을 중복하고 싶을때 받는 파라미터(개수, 타입)를 바꾸고 메서드의 이름을 같게하여, 사용하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
 
namespace _20190322
{
    class Program
    {
        static void Main(string[] args)
        {
            //오버로딩 예제
            Test test = new Test();
            Console.WriteLine(test.sum(13));
            Console.WriteLine(test.sum(1.1f, 3.3f));
 
            Console.ReadKey();
        }
    }
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190322
{
    class Test
    {
        public int sum(int a, int b)
        {
            return a + b;
        }
        public float sum(float a, float b)
        {
            return a + b;
        }
    }
}
 
cs



override

한정자는 상속된 메서드, 연산자의 기능을 확장하거나 수정하는 데 필요합니다.

사용하는 메서드or연산자는 같지만 그 기능이 다르고자 할때 사용한다!


메서드 오버라이드는 자식클래스에서 부모에게 상속받은 부모의 메서드를 재정의하여 사용하는 것이다.

부모클래스에서는 자식클래스가 오버라이드 할 수 있게 하기위해 앞에 virtual이라는 예약어를 메서드 앞에 붙인다.

자식클래스에서는 재정의 하여 사고싶으면 'override'라는 약어를 메서드 앞에 붙인다.//메서드 오버라이드는 너무 졸려서 맨정신일때 상속부터 다시 공부...........ㅠ
//연산자 오버라이드 예제(직접만든 벡터간의 합 연산자 +오버라이드)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
 
namespace _20190322
{
    class Program
    {
        static void Main(string[] args)
        {
            Vector2D Vector1 = new Vector2D(1f, 2f);
            Vector2D Vector2 = new Vector2D(2.2f, 3.3f);
 
            Console.WriteLine("({0}, {1})",(Vector1 + Vector2).x,(Vector1+Vector2).y);
 
            Console.ReadKey();
        }
    }
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190322
{
    class Vector2D
    {
        public float x, y;
        public Vector2D() { }
        public Vector2D(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
        public static Vector2D operator+(Vector2D a,Vector2D b)
        {
            return new Vector2D(a.x + b.x, a.y + b.y);
        }
    }
}
 
cs




//참고 사이트들

https://jshzizon.tistory.com/entry/C%EC%9D%98-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A51-2-%EC%97%B0%EC%82%B0%EC%9E%90-%EC%98%A4%EB%B2%84%EB%A1%9C%EB%94%A9

https://salkuma.wordpress.com/2014/02/11/%EC%97%B0%EC%82%B0%EC%9E%90-%EC%98%A4%EB%B2%84%EB%A1%9C%EB%94%A9-vs-%EC%98%A4%EB%B2%84%EB%9D%BC%EC%9D%B4%EB%94%A9/

https://jshzizon.tistory.com/entry/C%EC%9D%98-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A51-2-%EC%97%B0%EC%82%B0%EC%9E%90-%EC%98%A4%EB%B2%84%EB%A1%9C%EB%94%A9

: