게임 개발/C++

[C++] 연산자 오버로딩 - 2. 사칙 연산자

유행성바코드 2025. 3. 31. 14:04

연산자 오버로딩 - 2. 사칙 연산자

목차

  • 01. Intro
  • 02. 연산자 오버로딩
    • 사칙 연산자
    • 복합 대입 연산자
    • 전체 코드
  • 03. 마무리
  • 04. 연관 내용

01. Intro

오늘은 지난 포스팅 글에 이어 [사칙 연산자와 복합 대입 연산자의 오버로딩]을 알아보겠습니다.

 

 


02. 연산자 오버로딩

지난 포스팅에서 제작했던 Int 클래스에 대해 연산자 오버로딩을 추가로 작성하겠습니다.

#include <iostream>

using namespace std;

class Int
{
public:

	Int(int num) : _num(num) {}

	int getNum() const { return _num; }

	// 전위형 증감 연산자
	Int& operator++()
	{
		++_num;
		return *this;
	}
	
	Int& operator--()
	{
		--_num;
		return *this;
	}

	// 후위형 증감 연산자
	Int operator++(int)
	{
		Int temp = *this;
		++_num;
		return temp;
	}

	Int operator--(int)
	{
		Int temp = *this;
		--_num;
		return temp;
	}

private:
	int _num;
};

int main()
{
	Int num = 100;

	++(++num);
	// 102
	cout << num.getNum() << endl;

	// (num--)--;

	// 102
	cout << (num--).getNum() << endl;

	// 100
	cout << (--num).getNum() << endl;

	return 0;
}

저번에는 Int 클래스에 전위형과 후위형 증감 연산자 오버로딩을 추가했습니다.

이번에는 사칙 연산과 비교문에 대한 연산자 오버로딩을 추가하겠습니다.

 

사칙 연산자

Int operator+(const Int& other) const {}

사칙 연산자에 대한 함수는 위와 같은 형태를 가지고 있습니다.

 

위 형태로 덧셈, 뺄셈, 곱셈을 먼저 추가하겠습니다.

#include <iostream>

using namespace std;

class Int
{
public:

	Int(int num) : _num(num) {}

	int getNum() const { return _num; }

	// 전위형 증감 연산자
	Int& operator++()
	{
		++_num;
		return *this;
	}
	
	Int& operator--()
	{
		--_num;
		return *this;
	}

	// 후위형 증감 연산자
	Int operator++(int)
	{
		Int temp = *this;
		++_num;
		return temp;
	}

	Int operator--(int)
	{
		Int temp = *this;
		--_num;
		return temp;
	}

	// 사칙 연산자
	Int operator+(const Int& other) const
	{
		return Int(_num + other._num);
	}

	Int operator-(const Int& other) const
	{
		return Int(_num - other._num);
	}

	Int operator*(const Int& other) const
	{
		return Int(_num * other._num);
	}

private:
	int _num;
};
int main()
{
	Int num1 = 100;
	Int num2(10);

	cout << "덧셈 : " << (num1 + num2).getNum() << endl;
	cout << "덧셈 : " << (num1.operator+(num2)).getNum() << endl;

	cout << "뺄셈 : " << (num1 - num2).getNum() << endl;

	cout << "곱셈 : " << (num1 * num2).getNum() << endl;

	return 0;
}

사칙 연산자를 오버로딩하고, main 함수에서 실행하니 정상적으로 작동했습니다.

 

num1 + num2
num1.operator+(num2)

num1 + num2는 num1.operator+(num2)와 같은 의미로 사용됩니다.

 

나눗셈은 0으로 나눌 수 없으므로, 0의 값을 가진 데이터가 들어올 때, 별도의 처리를 해야 합니다.

여기서는 0으로 나눌 경우, 0의 값을 반환하도록 처리하겠습니다.

Int operator/(const Int & other) const
{
    if (other._num == 0) return Int(0);

    return Int(_num / other._num);
}
int main()
{
	Int num1 = 100;
    Int num2(10);
    
    cout << "나눗셈 : " << (num1 / num2).getNum() << endl;

}

 

 

복합 대입 연산자

+=와 같은 복합 대입 연산자는 사칙 연산자 오버로딩과 연관 없이 별도로 오버로딩해야 합니다.

Int& operator+=(const Int& other) {}

복합 대입 연산자는 위와 같은 형태를 가집니다.

자기 자신 데이터에 계산해서, 다시 대입하므로 참조형으로 반환해야 합니다.

또한, 자기 자신 데이터를 변경하므로 const 함수로 선언해서는 안됩니다.

 

위 형식을 바탕으로 복합 대입 연산자를 오버로딩하겠습니다.

// 복합 대입 연산자
Int& operator+=(const Int& other)
{
    _num += other._num;
    return *this;
}

Int& operator-=(const Int& other)
{
    _num -= other._num;
    return *this;
}

Int& operator*=(const Int& other)
{
    _num *= other._num;
    return *this;
}

Int& operator/=(const Int& other)
{
    if (other._num == 0) _num = 0;
    else _num /= other._num;

    return *this;
}
int main()
{
	Int num1 = 100;
	Int num2(10);

	cout << "덧셈 : " << (num1 += num2).getNum() << endl;
	cout << "덧셈 : " << (num1.operator+=(num2)).getNum() << endl;

	cout << "뺄셈 : " << (num1 -= num2).getNum() << endl;

	cout << "곱셈 : " << (num1 *= num2).getNum() << endl;

	cout << "나눗셈 : " << (num1 /= num2).getNum() << endl;

	return 0;
}

본인 데이터에 계속 연산을 하니, 이전과는 다른 결과가 나오는 것을 확인할 수 있습니다.

 

전체 코드

#include <iostream>

using namespace std;

class Int
{
public:

	Int(int num) : _num(num) {}

	int getNum() const { return _num; }

	// 전위형 증감 연산자
	Int& operator++()
	{
		++_num;
		return *this;
	}
	
	Int& operator--()
	{
		--_num;
		return *this;
	}

	// 후위형 증감 연산자
	Int operator++(int)
	{
		Int temp = *this;
		++_num;
		return temp;
	}

	Int operator--(int)
	{
		Int temp = *this;
		--_num;
		return temp;
	}

	// 사칙 연산자
	Int operator+(const Int& other) const
	{
		return Int(_num + other._num);
	}

	Int operator-(const Int& other) const
	{
		return Int(_num - other._num);
	}

	Int operator*(const Int& other) const
	{
		return Int(_num * other._num);
	}

	Int operator/(const Int & other) const
	{
		if (other._num == 0) return Int(0);

		return Int(_num / other._num);
	}

	// 복합 대입 연산자
	Int& operator+=(const Int& other)
	{
		_num += other._num;
		return *this;
	}

	Int& operator-=(const Int& other)
	{
		_num -= other._num;
		return *this;
	}

	Int& operator*=(const Int& other)
	{
		_num *= other._num;
		return *this;
	}

	Int& operator/=(const Int& other)
	{
		if (other._num == 0) _num = 0;
		else _num /= other._num;

		return *this;
	}

private:
	int _num;
};

int main()
{
	Int num1 = 100;
	Int num2(10);

	cout << "덧셈 : " << (num1 += num2).getNum() << endl;
	cout << "덧셈 : " << (num1.operator+=(num2)).getNum() << endl;

	cout << "뺄셈 : " << (num1 -= num2).getNum() << endl;

	cout << "곱셈 : " << (num1 *= num2).getNum() << endl;

	cout << "나눗셈 : " << (num1 /= num2).getNum() << endl;

	return 0;
}

 


03. 마무리

이번에 코드를 작성하면서, 사칙 연산 후에 getNum() 함수를 통해 데이터를 가져와야만 출력이 되는 불편함이 있었습니다.

다음 포스팅 글에서는 이를 해결해 보겠습니다.

 


04. 연관 내용

  • [C++] 연산자 오버로딩 - 1. 전위형 / 후위형 증감 연산자
 

[C++] 연산자 오버로딩 - 1. 전위형 / 후위형 증감 연산자

목차01. Intro02. 증감 연산자전위형 증감 연산자후위형 증감 연산자연산자 오버로딩 적용03. 마무리04. 연관 내용01. Intro오늘은 [전위형 & 후위형 증감 연산자]에 대한 특징을 알아보도록 하겠습니

epidemic-barcode.tistory.com

 

 


 

읽어주셔서 감사합니다.

틀린 내용 지적은 언제나 환영입니다!