c++

[C++]클래스와 함수에 대한 friend 선언

goblin- 2023. 4. 30. 18:17

friend 선언은 private 멤버의 접근을 허용하는 선언이다. 

  • A 클래스가 B 클래스를 대상으로 friend 선언을 하면, B클래스는 A클래스의 private 멤버에 직접 접근이 가능하다.
  • 단, A 클래스도 B 클래스의 private 멤버에 직접 접근이 가능하려면, B 클래스가 A 클래스를 대상으로 friend 선언을 해줘야 한다.
#include <iostream>
#include <cstring>
using namespace std;

class Girl;

class Boy{
private:
    int height;
    friend class Girl;
public:
    Boy(int len) : height(len){}
    void ShowYourFriendInfo(Girl &frn);
};

class Girl{
private:
    char phNum[20];
public:
    Girl(char *num){
        strcpy(phNum, num);
    }
    void ShowYourFriendInfo(Boy &frn);
    friend class Boy;
};

void Boy::ShowYourFriendInfo(Girl &frn){
    cout<<"her phone number: "<<frn.phNum<<endl;
}

void Girl::ShowYourFriendInfo(Boy &frn){
    cout<<"His height: "<<frn.height<<endl;
}

int main(void){
    Boy boy(170);
    Girl girl("010-1234-5678");
    boy.ShowYourFriendInfo(girl);
    girl.ShowYourFriendInfo(boy);
    return 0;
}

결과

her phone number: 010-1234-5678
His height: 170

위의 코드를 보면 Boy 클래스와 Girl 클래스 모두 각자 friend 클래스를 선언해 주었고 따라서 friend 클래스의 private 변수에 접근이 가능하였다.

 

함수의 friend 선언

전역함수를 대상으로도, 클래스의 멤버함수를 대상으로도 friend 선언이 가능하다. 물론 friend로 선언된 함수는 자신이 선언된 클래스의 private 영역에 접근이 가능하다.