판다코딩 c++ 연산자 오버로딩

개발자는엉금엉금·2022년 9월 21일
0

💡전 시간에 this포인터부분에서 topval함수로 private멤버변수와 참조자를 이용해서 비교한 것이 기억나는가? 그것을 응용해서 operator함수 오버로딩을 만들 수 있다.

  • Time operator+(Time&)로 선언하고, Time Time::operator+(Time& t)로 정의한다
  • operator함수로 class끼리 연산을 할 수 있다(단, 나눗셈은 0으로 나누면 런타임에러가 있기 때문에 제한적)

💻time.h

#include <iostream>
#ifndef TIME
#define TIME
using namespace std;
//연산자 오버로딩을 사용해서 class끼리 연산을 해보자.
class Time
{
private:
	int hours;
	int mins;
public:
	Time();
	Time(int, int);
	Time operator+(Time&);
	void show();
	~Time();
};
#endif

💻func.cpp

#include "time.h"

Time::Time()
{
	hours = mins = 0;
}

Time::Time(int h, int m)
{
	hours = h;
	mins = m;
}
//hours, mins 매개변수가 있는 생성자

Time Time::operator+(Time& t)
{
	
	Time sum;
	sum.hours = hours + t.hours;
	
	sum.mins = mins + t.mins;
	//일단 sum에 시간과 분을 저장
	sum.hours += sum.mins / 60;
	//60분이 넘어가면 1시간으로 변환해줘야하므로 몫 연산자를 사용
	
	sum.mins %= 60;
	return sum;

}

void Time::show()
{	
	cout << "시간:" << hours << endl;
	cout << "분:" << mins << endl;
	
}

Time::~Time()
{
}

  • public함수를 통해 ::연산자를 사용하여 private멤버변수에 직접 접근이 가능하다(그래서 hours,mins사용이 가능)
    📢주의:sum.hours += sum.mins / 60;부분에서 sum.hours = sum.mins/60으로 하면 day1+day2의 값이 아닌 변환된 부분만 "시간:"으로 출력됨

💻main.cpp

#include "time.h"

int main()
{
	Time day1(2, 30);
	Time day2(3, 45);

	day1.show();
	day2.show();
	Time total = day1 + day2;

	total.show();



	return 0;
}

  • operator함수를 사용할 때, day1.operator+(day2);로도 사용이 가능하다.

0개의 댓글