연산자 데이터형이 다를 때(가령, class와 int형타입) private멤버변수로 접근할 수 있는 함수
- 이항 피연산자를 필요로 한다
📢 public에 선언하고, 멤버함수가 아니므로 '::' 사용 범위 결정연산자와 friend 키워드를 함수 정의부분에 사용하지 않는다.
#include <iostream>
#ifndef TIME
#define TIME
using namespace std;
class Time
{
private:
int hours;
int mins;
public:
Time();
Time(int, int);
void show();
~Time();
friend Time operator*(int n, Time& t);
};
#endif
#include "time.h"
Time::Time()
{
hours = mins = 0;
}
Time::Time(int h, int m)
{
hours = h;
mins = m;
}
Time operator*(int n, Time& t)
{
Time result;
long resultMin = t.hours * n * 60 + t.mins * n;
result.hours = resultMin / 60;
result.mins = resultMin % 60;
return result;
}
void Time::show()
{
cout << "시간:" << hours << endl;
cout << "분:" << mins << endl;
}
Time::~Time()
{
}
#include "time.h"
int main()
{
Time t1(1, 20);
Time t2;
t2 = t1 * 3;
t2.show();
return 0;
}
#include <iostream>
#ifndef TIME
#define TIME
using namespace std;
class Time
{
private:
int hours;
int mins;
public:
Time();
Time(int, int);
Time operator*(int);
void show();
~Time();
friend Time operator*(int n, Time& t)
{
return t * n;
}
//friend함수를 헤더부분에서 inline으로 처리
};
#endif
#include "time.h"
Time::Time()
{
hours = mins = 0;
}
Time::Time(int h, int m)
{
hours = h;
mins = m;
}
Time Time :: operator*(int n)
{
Time result;
long resultMin = hours * n * 60 + mins * n;
result.hours = resultMin / 60;
result.mins = resultMin % 60;
return result;
}
void Time::show()
{
cout << "시간:" << hours << endl;
cout << "분:" << mins << endl;
}
Time::~Time()
{
}
#include "time.h"
int main()
{
Time t1(1, 20);
Time t2;
t2 = 3 * t1;
t2.show();
return 0;
}