본문 바로가기

.NET/C# Basic

연산자 메서드 operator +(), operator-() , 연산자 오버로딩?

반응형


연산자 메서드를 부르려면 해당 연산자를 사용하며,  
연산자를 사용하면 코드가 훨씬 직관적이기 때문에 이해하기 쉬워진다



using System;

class Point
{
    public int x;
    public int y;

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

    public override string ToString()
    {
        // (x,y) 값
        return String.Format("({0},{1})", x, y );
    }

 // + 연산자 메서드
 public static Point operator +(Point pt1, Point pt2)
 {
  return (new Point(pt1.x + pt2.x, pt1.y + pt2.y));
 }

 // - 연산자 메서드
 public static Point operator -(Point pt1, Point pt2)
 {
  return (new Point(pt1.x - pt2.x, pt1.y - pt2.y));
 }
}


class Class1
{
 static void Main(string[] args)
 {
  Point pt1 = new Point(100, 100);
  Point pt2 = new Point(100, 200);
  Point pt3, pt4;

  // Point 객체 + 연산
  pt3 = pt1 + pt2;
  pt4 = pt1 - pt2;

  Console.WriteLine("{0} + {1} = {2}__{3}", pt1, pt2, pt3, pt4);
 }
}



모르겠쌈~~~~~~~~! 갈쳐줘 ㅋㅋ


C#에서 제공하는 연산자
 C#에서 제공되는 연산자 중에서 일부 연산자를 클래스에 정의해서 쓸 수 있다
C# 연산자 중에서 연산자 오버로딩이 되는 것과 안 되는 것을 구분


연산자 오버로딩할 수 있는 연산자

  unary 연산자        + - ! ++ -- true false
  binary 연산자       + - * / % & | ^ << >>
  비교 연산자         == != < > <= >=

연산자 오버로딩할 수 없는 연산자

   &&, ||, [], ()
    +=, -=, *=, /=, %=
    = . ?: -> new is as sizeof typeof 등등