C++

Friend

David0903 2022. 2. 3. 00:05

1. 프렌드의 개념

C++ 클래스 외부에 작성된 함수를 클래스 내에 friend 키워드로 선언하여, 클래스의 멤버 함수와 동일한 접근 자격을 부여할 수 있다.

클래스 멤버 함수로를 적합하지 않지만 클래스의 private, protected 멤버를 접근해야 하는 특별한 경우, 프렌드로 선언

 

2. 프렌드 함수 선언

friend의 키워드를 사용하여 함수를 선언할 경우 컴파일러에게 해당 class의 멤버 변수에 접근하는 것을 허용해줌.

 

3. 선언 방법 1

외부함수 equals()를 Rect 클래스의 프렌드로 선언하는 것.

#include <iostream>
using namespace std;

// Rect를 객체로 사용하기 위해 미리 선언
class Rect;
bool equals(Rect r, Rect s);

class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width;
		this->height = height;
	}
	// friend를 통해 Rect의 멤버 접근 가능
	friend bool equals(Rect r, Rect s);
};

// 외부에 선언된 전역함수
bool equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

int main() {
	Rect a(3, 4), b(4, 5);
	if (equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
}

4. 선언 방법 2

RectManager 클래스의 equals 멤버 함수를 Rect 클래스의 프렌드로 선언.

#include <iostream>
using namespace std;

class Rect;

class RectManager {
public:
	bool equals(Rect r, Rect s);
};

class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width; 
		this->height = height;
	}
	// friend를 통해 equals 함수가 width, height에 접근 가능
	friend bool RectManager::equals(Rect r, Rect s);
};

bool RectManager::equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

int main() {
	Rect a(3, 4), b(4, 5);
	RectManager man;
	if (man.equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
}

 

5. 선언 방법 3

RectManager 클래스 전체를 Rect 클래스의 프렌드로 선언.

#include <iostream>
using namespace std;

class Rect;
class RectManager {
public:
	bool equals(Rect r, Rect s);
	void copy(Rect& destm ,Rect& src);
};
class Rect {
	int width, height;
public:
	Rect(int width, int height) {
		this->width = width; 
		this->height = height;
	}

	friend RectManager;
};

bool RectManager::equals(Rect r, Rect s) {
	if (r.width == s.width && r.height == s.height) return true;
	else return false;

}

void RectManager::copy(Rect& dest, Rect& src) {
	dest.width = src.width; dest.height = src.height;
}

int main() {
	Rect a(3, 4), b(4, 5);
	RectManager man;
	man.copy(b, a);
	if (man.equals(a, b)) cout << "equal" << endl;
	else cout << "not equal" << endl;
	
}

'C++' 카테고리의 다른 글

Template  (0) 2022.02.03
Operator Overloading  (0) 2022.02.03
Copy Constructor  (0) 2022.02.03
Lambda  (0) 2022.02.02
Iterator  (0) 2022.02.02