Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 Friend 클래스 및 함수


클래스의 friend 함수는 해당 클래스의 범위 외부에 정의되어 있지만 클래스의 모든 private 및 protected 멤버에 액세스할 수 있는 권한이 있습니다. 친구 함수의 프로토타입이 클래스 정의에 나타나더라도 친구는 멤버 함수가 아닙니다.

친구는 함수, 함수 템플릿, 멤버 함수 또는 클래스나 클래스 템플릿이 될 수 있으며, 이 경우 전체 클래스와 모든 멤버가 친구입니다.

함수를 클래스의 friend로 선언하려면 다음과 같이 friend 키워드를 클래스 정의에서 함수 프로토타입 앞에 둡니다. -

class Box {
double width;

public:
   double length;
   friend void printWidth( Box box );
   void setWidth( double wid );
};

ClassTwo 클래스의 모든 멤버 함수를 ClassOne 클래스의 친구로 선언하려면 ClassOne 정의에 다음 선언을 배치하십시오. -

friend class ClassTwo;

#include <iostream>
using namespace std;

class Box {
   double width;

   public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};

// Member function definition
void Box::setWidth( double wid ) {
   width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
   /* Because printWidth() is a friend of Box, it can
   directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}

// Main function for the program
int main() {
   Box box;

   // set box width without member function
   box.setWidth(10.0);

   // Use friend function to print the wdith.
   printWidth( box );

   return 0;
}

출력

이것은 출력을 제공합니다 -

Width of box: 10

함수가 클래스의 멤버가 아니더라도 해당 클래스의 멤버 변수에 직접 액세스할 수 있습니다. 이것은 특정 상황에서 매우 유용할 수 있습니다.