C++: friend
개요
- 다른 클래스나 함수에서 private 멤버에 대한 접근이 필요할 때 사용(단방향)
예제
- 코드
#include <iostream>
using namespace std;
class Test1 {
private:
int i;
friend class Test2;
friend void func();
};
class Test2 {
private:
Test1 t;
public:
Test2() { this->t.i = 1; }
int GetI() { return this->t.i; }
};
void func() {
Test1 t;
t.i = 1;
cout << t.i << endl;
};
int main() {
func();
Test2 t;
cout << t.GetI() << endl;
return 0;
}
- 실행 결과
1
1