언어/C++

[C++] 연산자 오버로딩 (이항연산자의 매개변수가 하나인 이유)

study_memo 2023. 10. 6. 00:46

연산자 오버로딩 개념을 공부하던 중에

아래코드에서 -는 이항 연산자인데 왜 매개변수를 하나만 받는 것인지 궁금해졌다..

#include <iostream>
using namespace std;

class Position
{
private:
	double x_;
	double y_;
public:
	Position(double x, double y);	// 생성자 
	void Display();
	Position operator-(const Position& other);	// - 연산자 함수 
};

int main(void)
{
	Position pos1 = Position(3.3, 12.5);
	Position pos2 = Position(-14.4, 7.8);
	Position pos3 = pos1 - pos2;
	
	pos3.Display();
	return 0;
}

Position::Position(double x, double y)
{
	x_ = x;
	y_ = y;
}

Position Position::operator-(const Position& other)
{
	return Position((x_ + other.x_)/2, (y_ + other.y_)/2);
}

void Position::Display()
{
	cout << "두 지점의 중간 지점의 좌표는 x좌표가 " << this->x_ << "이고, y좌표가 " << this->y_ << "입니다." << endl;
}

그리고 무엇보다...

Position Position::operator-(const Position& other)
{
	return Position((x_ + other.x_)/2, (y_ + other.y_)/2);
}

이 부분이 이해가 가지 않았다. 

return Position ((x_  ~~~~~~ 부분에서 x_는 도대체 어디서 나온 변수인걸까?

그리고 왜 매개변수는 하나인 걸까?

 

알고보니, Position pos3 = pos1 - pos2; 부분에서 pos1 객체를 기준으로 메소드 operator- 를 호출하고 매개변수로 pos2를 받는 것이었다. 

 

즉, 여기서 x_와 y_는 pos1의 x좌표값, y좌표값이고 

other.x_와 other.y_는 pos2의 x좌표값, y좌표값이었던 것이었다!

 

그래서 매개변수도 하나로 받아서 사용했던 것이다...