연산자 오버로딩

namu·2022년 10월 6일

함수와 달리
연산자는 피연산자의 개수/타입이 고정되어 있음.

연산자 함수도 멤버함수, 전역함수로 각각 만들 수 있다.

멤버 연산자 함수 version

  • a op b 형태에서 왼쪽으로 기준으로 실행됨(a가 클래스여야 가능. a를 '기준 피연산자'라고 함)
  • 한계) a가 클래스가 아니면 사용 못함

전역 연산자 함수 version

  • a op b 형태라면 a, b 모두를 연산자 함수의 피연산자로 만들어준다.

그럼 무엇이 더 좋은가? 그런 거 없음. 심지어 둘 중 하나만 지원하는 경우도 있다.

  • 대표적으로 대입 연산자 (a = b)는 전역 연산자로 못 만듦.
#include <iostream>

using namespace std;

class Position
{
public:
	Position operator+(const Position& arg)
	{
		Position pos;
		pos._x = _x + arg._x;
		pos._y = _y + arg._y;
		return pos;
	}

	Position operator+(int arg)
	{
		Position pos;
		pos._x = _x + arg;
		pos._y = _y + arg;
		return pos;
	}

	bool operator==(const Position& arg)
	{
		return _x == arg._x && _y == arg._y;
	}

	void operator=(int arg)
	{
		_x = arg;
		_y = arg;
	}

public:
	int _x;
	int _y;
};

Position operator+(int a, const Position& b)
{
	Position ret;

	ret._x = b._x + a;
	ret._y = b._y + a;

	return ret;
}

// 'operator='은(는) 멤버 함수여야 합니다. 컴파일 에러
// 두번째 인자로 대입하는 등 혼란이 있을 수 있기 때문에 문법적으로 막아둠.
void operator=(Position& a, int b)
{
	a._x = b;
	a._y = b;
}

int main()
{
	Position pos;
	pos._x = 0;
	pos._y = 0;

	Position pos2;
	pos2._x = 1;
	pos2._y = 1;

	Position pos3 = pos + pos2;
	pos3 = pos.operator+(pos2);

	Position pos4 = pos3 + 1;
	pos3.operator+(1);

	Position pos5 = 1 + pos3;
	operator+(1, pos3);

	bool isSame = (pos3 == pos4);

	Position pos6;
	pos6 = 5;

	//Position pos6 = 5; // int 하나 받는 생성자가 호출됨.

	return 0;
}

복사 대입 연산자

  • 대입 연산자 중, 자기 자신의 참조 타입을 인자로 받는 것

기타

  • 모든 연산자를 다 오버로딩할 수 있는 것은 아니다 (:: . .* 이런 건 안됨)
  • 모든 연산자가 다 2개 항이 있는 것은 아님. ++ --는 단항 연산자를 가짐.

증감 연산자 ++ --

  • 전위형 (++a) operator++()
  • 후위형 (a++) operator++(int)
	Position& operator=(positon& arg)
    {
    	_x = arg._x;
        _y = arg._y;
        rteurn *this;
    }
    
    Position& operator++()
    {
    	_x++;
        _y++;
        return *this;
    }
    
    Position operator++(int)
    {
    	Position ret = *this;
    	_x++;
        _y++;
        return ret;
mov eax,dword ptr [ebp+8]
mov ecx,dword ptr [ret]
mov edx,dword ptr [ebp-18h]
mov dword ptr [eax],ecx
mov dword ptr [eax+4],edx
mov eax,dword ptr [ebp+8]
    }
    
    ...
    
    ++(++pos3);
    
    pos5 = pos3++;
push 0
lea eax,[ebp-150h]
push eax
lea ecx,[pos3]
call Position::operator++ (...)
push eax
lea ecx,[pos5]
call Position::operator= (...)
profile
안녕하세요

0개의 댓글