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

Icarus<Wing>·2022년 9월 25일
0

💡stream연산자 오버로딩: ">>","<<"는 각각 istream,ostream의 연산자 표현인데 둘은 class의 멤버변수에 직접 접근할 수 없으므로 friend함수를 사용한다.

friend std::ostream& operator<<(std::ostream&, Time&);으로 선언하고,
std::ostream& operator<<(std::ostream& os,Time& t) { os<<t.hours<<"시간"<<t.mins<<",분"; return os;//os도 객체 }로 정의한다.

💻time.h

#include <iostream>
using namespace std;
#ifndef TIME
#define TIME
class Time
{
private:
	int hours;
	int mins;

public:
	Time operator+(Time&);//operator 연산자로 sum함수를 대체
	Time();
	Time(int, int);
	void show();//시간을 보여줌
	~Time();
	friend std::ostream& operator<<(std::ostream&, Time&);
};
#endif // !TIME

💻func.cpp

#include <iostream>
#include "time.h"

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

Time::Time(int h,int m)
{
	hours = h;
	mins = m;
}

Time Time:: operator+(Time& t)
{
	Time sum;//클래스를 선언하고 멤버변수에 접근을 안하면 디폴트값이 들어감
	sum.hours = hours + t.hours;
	sum.mins = mins + t.mins;
	sum.hours += sum.mins / 60;
	sum.mins %= 60;
	return sum;
}

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

std::ostream& operator<<(std:: ostream& os, Time& t)
{
	os << t.hours << "시간 " << t.mins << "분";
	return os;
}

Time::~Time()
{
}

💻main.cpp

#include <iostream>
#include "time.h"

int main()
{
	Time day1(4, 30);
	Time day2(5, 45);

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

	cout << total;




	return 0;
}
profile
모든 코드에는 이유가 있기에 원인을 파악할 때까지 집요하게 탐구하는 것을 좋아합니다.

0개의 댓글