C++ 기초 1

[C++] 6-2 단항 연산자의 오버로드

hbcho 2024. 1. 5. 08:12
단항 연산자의 오버로드

   데이터 항(오퍼랜드)이 한 개인 단항 연산자(unray operator; ++, - 등)를 멤버 연산자 함수로 오버로드할 때는 멤버 연산자 함수 operator#()는 매개변수를 사용하지 않는다. 연산자 함수의 호출은 연산에 사용된 오퍼랜드가 하게 되며, 그 오퍼랜드만이 포인터 this에 의해 연산자 함수에 암묵적으로 전달된다.

 

예제1
#include <iostream>
using namespace std;
class score {
private:
	int kor, eng;
public:
	score() {
		kor = 0; eng = 0;
	}
	score(int a, int b) {
		kor = a; eng = b;
	}
	void output(int& a, int& b) {	//int &a=x, int &b=y
		a = kor; b = eng;
	}
	score operator++();
	score operator++(int notused);
};

score score::operator++()	//선행 연산자 함수의 정의
{
	score temp;
	temp.kor = ++kor, temp.eng = ++eng;
	cout << "선행연상 ++ob:" << endl;
	return temp;	//score형의 객체를 반환
}

score score::operator++(int notused)	//후행 연산자 함수의 정의
{
	score temp;
	temp.kor = kor++, temp.eng = eng++;
	cout << "후행연상 ++ob:" << endl;
	return temp;	//score형의 객체를 반환
}

int main()
{
	score ob1(90, 70), ob2(80, 70), ob3, ob4;
	int x, y;
	ob3 = ++ob1;	//선행 연산자 함수 호출
	ob3.output(x, y);
	cout << "ob3.kor=" << x << ", ob3.eng=" << y << endl;
	ob1.output(x, y);
	cout << "ob1.kor=" << x << ", ob1.eng=" << y << endl;
	ob4 = ob2++;	//후행 연산자 함수 호출
	ob4.output(x, y);
	cout << "ob4.kor=" << x << ", ob4.eng=" << y << endl;
	ob2.output(x, y);
	cout << "ob2.kor=" << x << ", ob2.eng=" << y << endl;
	return 0;
}
실행 결과
선행연상 ++ob:
ob3.kor=91, ob3.eng=71
ob1.kor=91, ob1.eng=71
후행연상 ++ob:
ob4.kor=80, ob4.eng=70
ob2.kor=81, ob2.eng=71
 

 

예제2
#include <iostream>
using namespace std;
class score {
private:
	int kor, eng;
public:
	score() {
		kor = 0; eng = 0;
	}
	score(int a, int b) {
		kor = a; eng = b;
	}
	void output(int& a, int& b) {	//int &a=x, int &b=y
		a = kor; b = eng;
	}
	score operator-();
};

score score::operator-()
{
	kor = -kor;
	eng = -eng;
	return *this;
}

int main()
{
	score ob1(90, 70);
	int x, y;
	ob1 = -ob1;
	ob1.output(x, y);
	cout << "ob1.kor=" << x << ",ob1.eng=" << y << endl;
	return 0;
}
실행 결과
ob1.kor=-90,ob1.eng=-70

 

참고

1. 장인성 외 5인, (초보자도 쉽게 따라 할 수 있는) C++프로그래밍, 광문각, 2017.02.13