공부/C++

[C++] 6-2. 클래스와 함수에 대한 friend 선언

knhoo 2024. 10. 31. 16:19
728x90

클래스의 friend 선언

  • A클래스가 B클래스를 대상으로 friend 선언을 하면, B 클래스는 A 클래스의 private 멤버에 직접 접근이 가능하다.
  • 단, A클래스로도 B 클래스의 private멤버에 직접 접근이 가능하려면, B 클래스가 A클래스를 대상으로 friend선언을 해줘야 한다.

참고로 friend 선언은 클래스 내에  private영역이든지, public 영역이든지 어디에나 위치할 수 있다.

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;

class Girl;//Girl이라는 이름이 클래스의 이름임을 알림

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];
public:
	Girl(const char* num) {
		strcpy(phNum, num);
	}
	void ShowYourFriendInfo(Boy& frn);
	friend class Boy;//Boy클래스에 대한 friend 선언
};

void Boy::ShowYourFriendInfo(Girl& frn) {
	cout << "Her phone number: " << frn.phNum << endl;//private멤버에 접근
}

void Girl::ShowYourFriendInfo(Boy& frn) {
	cout << "His height: " << frn.height << endl;//private멤버에 접근
}

int main(void) {
	Boy boy(170);
	Girl girl("010-1234-5678");
	boy.ShowYourFriendInfo(girl);
	girl.ShowYourFriendInfo(boy);
	return 0;
}

friend class Girl;

이 문장에서 Girl의 클래스의 이름임을 알리는 동시에, Girl 클래스를 friend로 선언한다.


friend 선언의 주의점

friend 선언은 객체지향의 '정보 은닉'을 무너뜨리는 문법이기 때문에 위험할 수 있다.

필요한 상황에서만 소극적으로 사용해야 한다...


함수의 friend 선언

전역함수, 클래스의 멤버 함수를 대상으로도 friend 선언이 가능하다.

#include <iostream>
using namespace std;

class Point;//Point가 클래스의 이름임을 선언

class PointOP {
private:
	int opcnt;
public:
	PointOP() : opcnt(0)
	{ }

	Point PointAdd(const Point&, const Point&);
	Point PointSub(const Point&, const Point&);
	~PointOP() {
		cout << "Operation times: " << opcnt << endl;
	}
};

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 Point PointOP::PointSub(const Point&, const Point&);
	friend void ShowPointPos(const Point&);//함수 원형 선언이 포함됨
};

Point PointOP::PointAdd(const Point& pnt1, const Point& pnt2) {
	opcnt++;
	return Point(pnt1.x + pnt2.x, pnt1.y + pnt2.y);
}

Point PointOP::PointSub(const Point& pnt1, const Point& pnt2) {
	opcnt++;
	return Point(pnt1.x - pnt2.x, pnt1.y - pnt2.y);
}

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

	ShowPointPos(op.PointAdd(pos1, pos2));
	ShowPointPos(op.PointSub(pos1, pos2));
	return 0;
}

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

 

728x90