개발/C, C++

[C++] 연산자 오버로딩

huiyu 2019. 1. 3. 05:03


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
#include <iostream>
 
using namespace std;
 
class Point
{
private:
  int xpos, ypos;
public:
  Point(int x = 0int y = 0) : xpos(x), ypos(y)
  {  }
  void ShowPosition() const
  {
    cout<<'['<<xpos<<", "<<ypos<<']'<<endl;
  }
  Point operator+(const Point &ref)
  {
    Point pos(xpos + ref.xpos, ypos+ref.ypos);
    return pos;
  }
};
 
int main(void)
{
  Point pos1(34);
  Point pos2(1020);
  Point pos3 = pos1.operator+(pos2);
 
  pos1.ShowPosition();
  pos2.ShowPosition();
  pos3.ShowPosition();
 
  return 0;
}
cs

[실행결과]
[3, 4] [10, 20] [13, 24]

-> operator+ 함수는 Point객체의 덧셈을 위한 함수로, 예제에서 멤버함수 operator+를 호출하여 두 객체를 더하여 이를 반환하고 있다.

이는 아래와 같이 main을 변경하여도 같은 결과가 출력된다.
1
2
3
4
5
6
7
8
9
10
11
12
int main(void)
{
  Point pos1(34);
  Point pos2(1020);
  Point pos3 = pos1+pos2;
 
  pos1.ShowPosition();
  pos2.ShowPosition();
  pos3.ShowPosition();
 
  return 0;
}
cs

pos1 + pos2 는 pos1.operator+(pos2)와 동일한 문장이다.


- 연산자를 오버로딩 하는 두 가지 방법

 1) 멤버함수에 의한 연산자 오버로딩
 2) 전역함수에 의한 연산자 오버로딩

 이전 예제에선 pos1+pos2가 멤버함수를 이용하여서 pos1.operator+pos(2)로 해석됐다.
전역함수를 이용한 오버로딩을 하게 되면 pos1+pos2는 operator+(pos1, pos2)로 해석된다.

* 동일한 자료형을 대상으로 + 연산자를 전역함수, 그리고 멤버함수 기반으로 동시에 오버로딩 할 경우, 멤버함수 기반으로 오버로딩 된 함수가 전역함수 기반으로 오버로딩 된 함수보다 우선 호출된다.


전역함수 기반의 오버로딩

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
#include <iostream>
 
using namespace std;
 
class Point
{
private:
  int xpos, ypos;
public:
  Point(int x = 0int y = 0) : xpos(x), ypos(y)
  {  }
  void ShowPosition() const
  {
    cout<<'['<<xpos<<", "<<ypos<<']'<<endl;
  }
 
  friend Point operator+(const Point &pos1, const Point &pos);
};
 
Point operator+(const Point &pos1, const Point &pos)
{
  Point pos(pos1.xpos + pos2.xpos, pos1.ypos + pos2.ypos);
  return pos;
}
 
int main(void)
{
  Point pos1(34);
  Point pos2(1020);
  Point pos3 = pos+pos2;
 
  pos1.ShowPosition();
  pos2.ShowPosition();
  pos3.ShowPosition();
 
  return 0;
}
 
cs

-> operator+함수를 friend 선언하여 Point 클래스의 private 영역에 접근 가능, operator+의 연산자 오버로딩 선언


*오버로딩이 불가능한 연산자의 종류

 연산자

설명 

 멤버 접근 연산자

.*

멤버 포인터 연산자

::

범위 지정 연산자

?:

조건 연산자(3항 연산자)

sizeof

 바이트 단위 크기 계산

typeid

RTTI 관련 연산자

static_cast

형변환 연산자

dynamic_cast

형변환 연산자

const_cast

형변환 연산자

reinterpret_cast

형변환 연산자


*멤버함수 기반으로만 오버로딩이 가능한 연산자

 연산자

설명 

=

대입 연산자 

()

함수 호출 연산자 

[]

배열 접근 연산자(인덱스 연산자) 

->

멤버 접근을 위한 포인터 연산자 

-> 객체를 대상으로 진행해야 의미가 있는 연산자


*연산자 오버로딩 시 주의사항

 - 본래의 의도를 벗어난 형태의 연산자 오버로딩은 피한다.
 - 연산자의 우선순위와 결합성은 바뀌지 않는다.
 - 매개변수의 디폴트 값 설정이 불가능하다.
 - 연산자의기본 기능을 변경하는 형태의 오버로딩은 허용되지 않는다.

1
2
3
4
5
int operator+(const int num1, const int num2)   // 정의 불가능
{
  return num1*num2;
}
 
cs


윤성우 C++ 열혈 프로그래밍 10-1 연산자 오버로딩의 이해와 유형

728x90
반응형