관리 메뉴

드럼치는 프로그래머

[C/C++] friend 함수 본문

★─Programing/☆─C | C++

[C/C++] friend 함수

드럼치는한동이 2009. 11. 9. 14:19

-------------------------------------------------------------

#include <iostream>
using std::cout;
using std::endl;

class Counter
{
    int val;

public:
    Counter() {
        val = 0;
    }
    void Print() const {
        cout << val << endl;
    }
   
    friend void SetX(Counter& c, int val); // (1)
};

void SetX(Counter& c, int val)   // (2)
{
    c.val = val;
}

int main()
{
    Counter cnt;
    cnt.Print();
   
    SetX(cnt, 2002);
    cnt.Print();
   
    return 0;
}

-------------------------------------------------------------
(2)는 전역함수.
(1)은 전역함수 void SetX(..)를 friend로 선언.
friend 선언은 private나 public과 같은 접근 제어 키워드와는 상관이 없다.
따라서 클래스 내 어디에서든 선언이 가능하다.


friend 선언은 클래스들 간에도 가능하다.
-------------------------------------------------------------

#include <iostream>
using std::cout;
using std::endl;

class AAA
{
private:
    int data;
    friend class BBB; // (1)
};

class BBB
{
public:
    void SetData(AAA& aaa, int val) {
        aaa.data = val;  // (2)
    }
};

int main()
{
    AAA aaa;
    BBB bbb;
   
    bbb.SetData(aaa, 10);
    return 0;
}

-------------------------------------------------------------
(1)에서 class AAA가 class BBB를 friend로 선언.
(2)에서 class AAA의 private 영역에 접근.

friend는 단방향성을 지닌다. 위에서 AAA가 BBB를 friend로 선언했지만
BBB는 AAA를 friend로 선언하지 않았다.

* 추가설명

friend 선언은 한 방향으로만 접근할수 있다. 클래스 BBB가 클래스AAA의 친구이지만

클래스 AAA는 클래스 BBB의 친구가 아니다.

클래스 BBB가 클래스 AAA를
친구라고 선언하기 않았기 때문이다.

그래서 클래스 AAA에서는 클래스 BBB의 private 데이터 멤버를 접근할 수 없다.



[출처]
[정리C++]friend|작성자 투더리


Comments