2013. 11. 21. 22:05 C언어

c++ 공부 요점정리 9








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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// =====================================================
// 24 friend 선언
// =====================================================
// friend 로 선언되어지는 대상은 클래스가 될 수도있고
//
// 전역함수가 될 수 도잇다.
// 
// friend로 선언되면 private 영역 접근을 허용한다.
//
// 전역함수에게 private 영역 접근 허용
//
// 예제 1
//
#include <iostream>
using std::cout;
using std::endl;

class Counter
{
private:
	int val;

public:
	Counter() { 
		val=0;
	}
	void Print() const {
		cout<<val<<endl;
	}
		
	//전역함수를 friend 선언.
	friend void SetX(Counter& c, int val);  
};

void SetX(Counter& c, int val) // 전역함수.
{
	c.val=val;
	// Counter 클래스의 private 영역에 접근할 수 있다.
	// Counter 클래스에서 SetX를 friend로 선언했기 때문에	
}

int main()
{
	Counter cnt;
	cnt.Print();

	SetX(cnt, 2002);
	cnt.Print();

	return 0;
}

//
// 예제 2
//
#include <iostream>
using std::cout;
using std::endl;

class AAA
{
private:
	int data;
	friend class BBB;  // class BBB를 friend로 선언함!
};

class BBB
{
public:
	void SetData(AAA& aaa, int val){
		aaa.data=val; //class AAA의 private 영역 접근!
		
		// AAA 클래스에서 BBB 클래스를
		
		// friend로 선언했기 때문에
		
		// BBB 클래스에서 AAA 클래스의
		
		// private 영역에 접근할 수 있지만
		
		// AAA 영역에서 BBB 클래스의 private 영역에
		
		// 접근하는 것은 불가능하다(단방향성)
	}
};

int main()
{
	AAA aaa;
	BBB bbb;

	bbb.SetData(aaa, 10);

	return 0;
}

// friend 선언의 유용성

// : 유용하지 않다.

//   정보 은닉에 위배되는 개념

//   연산자 오버로딩에서 유용하게 사용

//   그 외에는 사용을 권장하지 않음

//   연산자 오버로딩에서는 제외하고는

//   friend 선언으로만 해결가능한 문제는 없다.










'C언어' 카테고리의 다른 글

c++ 공부 요점정리 11  (0) 2013.11.21
c++ 공부 요점정리 10  (0) 2013.11.21
c++ 공부 요점 정리 8  (0) 2013.11.20
c++ 공부 요점 정리 7  (0) 2013.11.20
SIGINT, SIGQUIT으로 프로그램 종료  (0) 2013.11.18
Posted by 뮹실이

최근에 달린 댓글

06-10 04:15
Yesterday
Today
Total