프랜드 클래스
클래스간에 멤버에 자유롭게 접근할 필요가 있을 경우 클래스를 플랜드로 지정하여 사용할 수 있다.
실습 6-2
#include <iostream>
using namespace std;
class Position {
friend class Color; //Position과 Color클래스는 서로 friend
private:
int cx, cy, cr;
public:
Position(int m_x, int m_y, int m_r) {
cx = m_x;
cy = m_y;
cr = m_r;
}
};
class Color {
private:
int r, g, b;
public:
Color(int m_r, int m_g, int m_b) {//생성자
r = m_r;
g = m_g;
b = m_b;
}
void GetInfo(Position& p);
};
void Color::GetInfo(Position& p) {
cout << "RGB:: " << r << "," << g << "," << b << endl;
cout << "Position:: " << p.cx << "," << p.cy << "," << p.cr << endl;
}
int main() {
Color C(255, 255, 255);
Position P(100, 100, 10);
C.GetInfo(P);
return 0;
}
5번째 줄에서는 Color 클래스가 Position 클래스의 프랜드로 지정되었다.
Color의 모든 멤버 함수들은 Position의 모든 멤버에 마음대로 접근할 수 있다.
GetInfo()함수는 Color 클래스의 멤버 함수이지만 Color 클래스가 Position 클래스의 프랜드로 지정되었으므로 GetInfo() 함수는 Posision 객체의 모든 멤버를 읽을 수 있다.
이처럼 두 개의 클래스가 상호 협조적으로 동작해ㅑㅇ 하는 경우 프랜드를 지정하여 편리하게 접근할 수 있따.
프랜드 멤버함수
프랜드 멤버 함수는 클래스의 특정 멤버 함수만 프랜드로 지정하여 반드시 필요한 함수에 대해서만 접근을 허락하는 것이다.
실습 예제 6-3 :
#include <iostream>
using namespace std;
class Color;
class Position {
private:
int cx, cy, cr;//원의 중심 좌표와 반지름
public:
Position(int m_x, int m_y, int m_r) {
cx = m_x;
cy = m_y;
cr = m_r;
}
void GetInfo(Color& c);
};
class Color {
friend void Position::GetInfo(Color& c);
private:
int r, g, b;//원 내부 색상
public:
Color(int m_r, int m_g, int m_b) {
r = m_r;
g = m_g;
b = m_b;
}
};
void Position::GetInfo(Color& c) {
cout << "Position:: " << cx << "," << cy << "," << cr << endl;
cout << "RGB:: " << c.r << "," << c.g << "," << c.b << endl;
}
int main() {
Position P(100, 100, 10);
Color C(255, 255, 255);
P.GetInfo(C);
return 0;
}
14번째 줄에서 Position클래스의 GetInfo()멤버 함수를 Color 클래스의 플내드로 지정하였다.
그러므로 GetInfo()함수는 Color클래스의 멤버에들에 자유롭게 접근할 수 있다.
단, Posision클래스의 다른 멤버 함수들은 Color클래스에 함부로 접근할 수 없다.
프랜드를 지정하면 public영역 멤버뿐만 아니라 protected영역이나 private영역의 멤버 함수나 멤버 함수에 자유롭게 접근할 수 있다.
책 : 이게 진짜 c++프로그래밍이다.
'c++' 카테고리의 다른 글
25. [C++] 클래스에서의 static키워드 (0) | 2023.01.21 |
---|---|
24. [C++] static과 const 멤버 (0) | 2023.01.21 |
22. [C++] friend (0) | 2023.01.20 |
[C++] 2가지 call by reference(주솟값, 참조자 이용) (0) | 2023.01.20 |
20. [C++] 객체 배열 (0) | 2023.01.20 |