C++
Friend
GOD03219
2018. 9. 19. 13:33
friend
단점: 캡슐화가 파괴될 위험이 있다.
장점: 코드의 확장
1. class
2. member function 잘 안쓰임
3. function 제일 잘 쓰인다.
function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 |
#include<iostream>
using namespace std;
class A
{
int a;
public:
friend void disp();
};
void disp()
{
A aa;
aa.a = 100; // A클래스에서 friend로 선언했기 때문에 A의 private int a에 접근가능 ; 캡슐화 파괴
cout << aa.a << endl;
}
void main() {
disp();
} |
cs |
friend class
#include<iostream>using namespace std;class A{friend class B; // B를 친구로 등록int a; // B에서 A클래스의 private 접근 가능};class B{A aa;public:void dispA(){aa.a = 10;cout << aa.a << endl;}};void main() {B bb;bb.dispA();}