Friend function: member function이 아닌 함수가 private data에 access할 수 있게 해주는 C++ 메커니즘.
Method(member func)만 privte data에 access하는 것은 너무 엄격하여 특정 프로그래밍 문제를 해결하지 못하는 경우가 있다. Friend 함수는 member function이 가지는 동등한 접근 권한을 가진다
어떤 경우에 필요할까?
Binary operator의 경우.
A = B*2.75; //A = B.operator*(2.75)
A = 2.75*B; //이 또한 가능해야 하지만 위 operator overloading에는 대응 안된다. 왼쪽 operand가 object가 아니기 때문.
이때, Time class는 friend 함수로 다음을 제공한다
Friend Time operator*(double m, const Time& t); //class내 선언. Class designer는 friend 함수의 prototype을 선언해둔다. (주인이 어떻게(how) 이용하라고 친구에게 허락한다)
Time operator*(double m, const Time& t) //class 외부의 definition. class를 사용하는 입장의 개발자가 friend 함수를 구현한다 (친구는 class 내부의 데이터를 접근한다)
{
Time result;
long totalminutes = t.hours * mult * 60 + t.minutes*mult;
result.hours = totalminutes/60;
result.minutes = totalminutes % 60;
return result;
}
사실 다음과 같이 함으로써 friend function을 사용치 않을 수도 있다.
Time operator*(double m, const Time& t)
{
return t*m; //t.operator*(m)을 사용
}
그럼에도 불구하고 friend로 만드는 것이 바람직하다.
잇점: 이 friend 함수가 class의 공식 interface로 된다. 이 friend 함수가 private data에 직접 접근할 필요가 생겼을 때, class 선언은 그대로 두고 function definition만 바꾸면 된다.
** 클래스 설계에 따라서는 간혹, 특별히 그 클래스에 대한 데이터형 변환을 정의했을 경우에, 멤버가 아닌 버전이 유리할 수도 있다.
<<의 overloading
cout << x << y; //(cout<<x) << y; 와 동일
ostream& operator<<(ostream& os, const Time& t)
{
os<< t.hours <<”시간, “ << t.minutes <<”분”;
return os; //ostream객체를 return하므로 (cout<<x)<<y가 가능함
}
Reference: http://callibri.egloos.com/2955544