C++.4 객체 연산자 오버라이딩

lsw·2021년 4월 3일
0

C++

목록 보기
4/8
post-thumbnail

1. 내용

특정 객체를 해당 연산자의 피연산자로 하여 어떠한(사용자가 지정할) 처리를 할 수 있도록 하는 "연산자 오버라이딩"에 대해 알아보자


2. 종류

  • 멤버 내 / 외 연산자 오버라이딩 함수
  • 전위 증/감소 연산자 오버라이딩
  • 후위 증/감소 연산자 오버라이딩

3. 코드(상기 종류 함수 통합 제시)

#include <iostream>
using namespace std;

class Point
{
  int xpos, ypos;
  public:
  Point(int x, int y)
  : xpos(x), ypos(y)
  {
  }

// 1. '+'연산자 멤버내 오버라이딩
  Point operator+(Point & pos2) // 피연산자 우측 객체 pos2
  // + 우측 피연산자 = 인자(pos) / 좌측피연산자 = 함수접근 본체
  {
    Point pcopy(xpos + pos2.xpos, ypos + pos2.ypos);
    return pcopy;
  }

// '+='연산자 멤버내 오버라이딩
  Point & operator+=(Point & pos2) // 피연산자 우측 객체 pos2
  {
    xpos += pos2.xpos; // 직접 값을 초기화
    ypos += pos2.ypos;
    return *this; // 연산의 주체가 되는 객체 반환
  }

// 전위연산자 '++ ~' 멤버내 오버라이딩
  Point & operator++() // 피연산자는 연산의 주체가 됨
  {
    xpos++;
    ypos++;
    return *this;
  }

// 멤버 외(전역) 오버라이딩, 멤버변수 접근을 위해 friend지정
  friend Point  operator-(Point & pos1, Point & pos2);
  friend Point & operator-=(Point & pos1, Point & pos2);

// 후위연산자는 두번째 인자로 "int"가 들어가야 함
  friend const Point  operator--(Point & pos1, int);
// 연산 완료 후 점 출력
  void Showpoint() const
  {
    cout << "[x,y] = " << xpos << "," << ypos << endl; 
  }
};

// 매개변수는 함수 지시자 본체, 인자1 = 2개
Point operator-(Point & pos1, Point & pos2)
{
// pcopy 객체 생성으로 Point 클래스 생성자 호출
  Point pcopy(pos1.xpos - pos2.xpos , pos1.ypos - pos2.ypos);
  return pcopy; // 객체 값을 변경하는것이 아닌 연산결과만 출력하는 것이니..
}

// 감소 초기화된 본체 반환
Point & operator-=(Point & pos1, Point & pos2)
{
  pos1.xpos -= pos2.xpos;
  pos1.ypos -= pos2.ypos;
  return pos1;
}

// 두번째 인자로 'int'를 받으며 후위증가임을 알림
const Point  operator--(Point & pos1, int)
{
  // 반환은 감소 전 원객체의 복사 객체로 하고, 원객체 내부 변수는 실제 초기화(감소)
  Point  pref = pos1;
  pos1.xpos --;
  pos1.ypos --;
  return pref;
}

// 결과 출력
int main()
{
  Point pos1={1,2}, pos2={5,7};
  (pos1 + pos2).Showpoint(); // (6,9)
  (pos1 - pos2).Showpoint(); // (-4,-5)
  pos1 += pos2; 
  pos1.Showpoint(); // (6,9)
  pos1 -= pos2; 
  pos1. Showpoint(); // (1,2)
  (++pos1).Showpoint(); // (2,3)
  (++(++pos1)).Showpoint(); // (4,5)
  pos1--.Showpoint(); // 증가되기 전 pos1의 복사체의 멤버가 출력 (4,5)
  pos1.Showpoint(); // 증가된 pos1의 멤버가 출력 (3,4)
  return 0;
}

4. 결과

5. 결론

연산자는 기본형만을 피연산자로 갖는게 아닌 연산자 오버라이딩을 통해 객체 또한 피연산자로 가질 수 있다.

profile
미생 개발자

0개의 댓글