💡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&);
Time();
Time(int, int);
void show();
~Time();
friend std::ostream& operator<<(std::ostream&, Time&);
};
#endif
💻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;
}