Friend인 클래스 및 클래스 멤버 함수
클래스 멤버 함수는 다른 클래스에서 friend로 선언될 수 있습니다. 다음 예제를 참조하십시오.
// classes_as_friends1.cpp
// compile with: /c
class B;
class A {
public:
int Func1( B& b );
private:
int Func2( B& b );
};
class B {
private:
int _b;
// A::Func1 is a friend function to class B
// so A::Func1 has access to all members of B
friend int A::Func1( B& );
};
int A::Func1( B& b ) { return b._b; } // OK
int A::Func2( B& b ) { return b._b; } // C2248
위의 예제에서는 A::Func1( B& ) 함수에만 B 클래스에 대한 friend 액세스 권한이 부여됩니다. 따라서 전용 멤버 _b에 대한 액세스는 A 클래스의 Func1에서 올바르지만 Func2에서는 올바르지 않습니다.
friend 클래스는 모든 멤버 함수가 클래스의 friend 함수인 클래스입니다. 즉, 멤버 함수가 다른 클래스의 전용 및 보호된 멤버에 액세스할 수 있습니다. B 클래스의 friend 선언이 다음과 같다고 가정합니다.
friend class A;
이 경우 A 클래스의 모든 멤버 함수에 B 클래스에 대한 freind 액세스 권한이 부여되었습니다. 다음 코드는 friend 클래스의 예입니다.
// classes_as_friends2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class YourClass {
friend class YourOtherClass; // Declare a friend class
public:
YourClass() : topSecret(0){}
void printMember() { cout << topSecret << endl; }
private:
int topSecret;
};
class YourOtherClass {
public:
void change( YourClass& yc, int x ){yc.topSecret = x;}
};
int main() {
YourClass yc1;
YourOtherClass yoc1;
yc1.printMember();
yoc1.change( yc1, 5 );
yc1.printMember();
}
friendship은 이와 같이 명시적으로 지정되지 않은 경우 상호적이 아닙니다. 위의 예제에서 YourClass의 멤버 함수는 YourOtherClass의 전용 멤버에 액세스할 수 없습니다.
관리되는 형식에는 friend 함수, friend 클래스 또는 friend 인터페이스가 있을 수 없습니다.
friendship은 상속되지 않습니다. 즉, YourOtherClass에서 파생된 클래스는 YourClass의 전용 멤버에 액세스할 수 없습니다. friendship은 전이적이 아니므로 YourOtherClass의 friend인 클래스는 YourClass의 전용 멤버에 액세스할 수 없습니다.
다음 그림에서는 Base, Derived, aFriend 및 anotherFriend라는 네 가지 클래스 선언을 보여 줍니다. aFriend 클래스만 Base 전용 멤버(및 Base에서 상속했을 수 있는 모든 멤버)에 직접 액세스할 수 있습니다.
friend 관계의 의미