카테고리 없음

friend (private 멤버 접근 허용)

zuyo 2019. 5. 9. 01:59
반응형

friend

- 다른 클래스나 외부 함수에 자신의 private 멤버 접근을 허용

* 선언은 클래스 내에 아무데나 해줘도 상관 없음
* 꼭 필요할 때 말고는 가급적 사용하지 않는 것을 추천

 

1. 다른 클래스를 friend로 선언하는 예

class Boy {
private:
	int height;
	friend class Girl; // Girl 클래스를 friend로 선언

public:
	Boy(int len) : height(len) { }
	void ShowYourFriendInfo(Girl& frn);
};

class Girl {
private:
	char phNum[20];
	friend class Boy; // Boy 클래스를 friend로 선언

public:
	Girl(char* num) {
		strcpy(phNum, num);
	}
	void ShowYourFriendInfo(Boy& frn);
};

void Girl::ShowYourFriendInfo(Boy& frn) {
	cout<<"His height: "<}

void Boy::ShowYourFriendInfo(Girl& frn) {
	cout<<"Her phone number: "<}

void main() {
	Boy boy(170);
	Girl girl("010-1234-5678");

	boy.ShowYourFriendInfo(girl);
	girl.ShowYourFriendInfo(boy);
}

2. 다른 클래스의 멤버 함수나 외부 전역 함수를 friend로 선언하는 예

class PointOP 
{
public:
	PointOP() : opcnt(0) { }
	Point PointAdd(const Point&, const Point&);
	Point PointSub(const Point&, const Point&);
};

class Point 
{
private:
	int x;
	int y;

public:
	Point(const int& xpos, const int& ypos) : x(xpos), y(ypos) { }
	friend Point PointOP::PointAdd(const Point&, const Point&); // 다른 클래스의 멤버 함수를 friend로 선언
	friend void ShowPointPos(const Point&); // 외부 전역 함수를 friend로 선언
};

Point PointOP::PointAdd(const Point& pnt1, const Point& pnt2) {
	return Point(pnt1.x + pnt2.x, pnt1.y + pnt2.y); // friend이기 때문에 Point의 private 멤버(x, y)에 접근이 가능
}

void ShowPointPos(const Point& pos) {
	cout << "x: " << pos.x << ", ";
	cout << "y: " << pos.y << endl;
}

void main() {
	Point pos1(1,2);
	Point pos2(2,4);
	PointOP op;

	ShowPointPos(op.PointAdd(pos1,pos2));
}
반응형