티스토리 뷰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication11;
 
namespace ConsoleApplication1
{
    class OperatorTest
    {
        static void Main(string[] args)
        {
            Operators o1 = new Operators(1);
            Operators o2 = new Operators(2);
            Operators o3 = o1 - o2;
            
            Console.WriteLine(o3.number);
 
        }
 
    }
}
 
 
namespace ConsoleApplication11
{
 
    class Operators
    {
        public int number;
 
 
        public Operators(int number)
        {
            this.number = number;
        }
 
        public static Operators operator -(Operators o1, Operators o2)
        {
 
            return new Operators(o1.number + o2.number);
        }
    }
 
}

c#에서는 연산자 오버로딩이라는게 존재하는데..

말그대로 연산자를 입맛에 맞게 변경할 수 있다.

이를테면 -연산을 다른 사칙연산 처럼 사용 할 수 있고, 다른 방식으로 값을 추려낼수도 있다. 

접했을 때의 느낌은 그냥 특이하다 정도이다.

굳이 써야할 필요가 있나 싶을 정도로 필요가 있어 보이진 않는다..

 

연산자 오버로드의 작성법은 간단하다. 연산 수행을 바꾸고 싶은 클래스에 연산자 오버로딩 함수를 정의하면된다.

 

public static 타입 operator 연산자(타입 변수명1, 타입 변수명2){

     //타입을 반환하는 코드

}

 

 

알아야 할 것은 프로그래밍 언어의 모든 연산자에 대해서 연산자 오버로딩을 수행할 수는 없다 일부만 가능하다..

 

 

 

 

Comments
최근에 올라온 글
최근에 달린 댓글
TAG
more
Total
Today
Yesterday