Minwoo Dev.
[C++] friend 본문
728x90
반응형
SMALL
friend
C++에서의 friend 선언은 해당 객체에 대해 접근을 허용할 때 사용한다.
한마디로, 해당 객체의 private 영역에 대한 접근을 허용하게 해주는 키워드인 셈이다.
자세한 건 예시를 통해 확인해보자.
우선, friend 선언은 가급적 사용을 지양해야 하며, 되도록 사용하지 않도록 프로그래밍 해야한다는 점을 기억하자
friend 선언이 사용되는 경우는 크게 두 가지가 존재한다.
1. 해당 객체가 다른 객체의 멤버에 대해 접근이 가능하도록 하고싶을 때
#include<iostream>
#include<cstring>
using namespace std;
class Girl;
class Boy{
private:
int height;
friend class Girl; // friend 선언
public:
Boy(int len):height(len){}
void ShowYourFriendInfo(Girl &frn);
};
class Girl{
private:
char phNum[20];
public:
Girl(char* num){
strcpy(phNum, num);
}
void ShowYourFriendInfo(Boy &frn);
friend class Boy; // friend 선언
};
void Boy::ShowYourFriendInfo(Girl &frn){
cout << "Her phone Number " << frn.phNum << endl;
}
void Girl::ShowYourFriendInfo(Boy & frn){
cout << "His height : " << frn.height << endl;
}
int main(void){
Boy boy(170);
Girl girl("010-1234-5678");
boy.ShowYourFriendInfo(girl);
girl.ShowYourFriendInfo(boy);
return 0;
}
friend 선언을 하면, 해당 클래스(객체)의 private 영역까지 접근이 가능하다.
위 경우에, Girl 클래스에서 Boy를 friend 선언하였고, Boy 클래스에서도 Girl 을 friend로 선언하여 서로의 멤버 변수에 접근할 수 있게 되었다.
위처럼 서로의 private 영역의 데이터에 정상적으로 접근한 것을 확인할 수 있다.
2. 외부의 함수에서 클래스 내부의 데이터를 사용하고자 할 때
이 경우는 나중에 연산자 오버로딩의 구현에서도 많이 사용되는데, 특정 함수에서 클래스 내부의 변수에 접근할 수 있도록 허용하는 것이다.
#include<iostream>
using namespace std;
class Point{
private:
int xpos, ypos;
public:
Point(int x=0, int y=0):xpos(x),ypos(y){}
void SetPosition(int x, int y){
xpos = x;
ypos = y;
}
void ShowPosition() const{
cout << "[" << xpos << ", " << ypos << "]" << endl;
}
friend void SetX(Point &pos, int x); // friend 선언을 하지 않으면 pos.xpos 접근 불가!
};
void SetX(Point& pos, int x){
pos.xpos = x;
}
int main(void){
Point pos(1, 3); // 1, 3으로 점 설정
pos.ShowPosition();
pos.SetPosition(3, 4); // 3, 4로 점 변경
pos.ShowPosition();
SetX(pos, 7); // x값을 7로 변경 -> 7, 4
pos.ShowPosition();
return 0;
}
위 코드에서는 Point 클래스의 외부에 x값만을 재설정하는 SetX() 가 존재한다.
SetX()는 변경할 점 Point와 x값을 받아서 수정하게 된다.
여기서, SetX()함수를 Point 클래스에 friend 선언을 해두지 않았다면, SetX() 함수에서 pos.xpos라는 값에 접근할 수 없게 될 것이다.
왜냐하면, xpos는 Point클래스의 private 영역에 속하기 때문이다.
따라서 우리는 friend 선언을 통해서, 외부에 존재하는 함수인 SetX()가 Point 클래스의 private 영역에 접근할 수 있도록 만든 것이다.
위 코드의 결과는 아래와 같다.
728x90
반응형
LIST
'C++' 카테고리의 다른 글
[C++] 일반적인 전역 변수와 static 전역 변수의 차이점 (0) | 2024.06.28 |
---|---|
[C++] static, 클래스 안에서의 static (0) | 2024.06.28 |
[C++] 복사 생성자 (Copy Constructor) (0) | 2024.06.27 |
[C++] malloc과 new 의 차이점 (0) | 2024.06.25 |
[C++] 문자열을 나타내는 방식, const char*, char*, string (0) | 2024.05.25 |