Skip navigation

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.