본문 바로가기

언어/C++

프렌드 함수

프랜드함수: 클래스 내에 friend 키워드로 선언된 외부 함수 

 

두 Rect 객체를 비교하는 bool equals (Rect r ,Rect s ) 를 Rect 클래스에 프랜드 함수로 작성하기 

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Rect{
	int width;
	int height;
	
	public:
		Rect(int width, int height){
			this->width=width;
			this->height=height;
		}
		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(int argc, char** argv) {
	
	Rect a(3,4);
	Rect b(4,5);
	if(equals(a,b)) cout <<"equal" <<endl;
	else cout <<"not equal" << endl;
	
	return 0;
}

 

<프랜드 멤버 선언 > 

다른 클래스의 멤버 함수를 클래스의 프랜드 함수로 선언할 수 있다 

 

RectManager 클래스의 equals () 멤버 함수를 Rect 클래스의 프렌드로 선언하라

 

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Rect;

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

class Rect{
	int width;
	int height;
	
	public:
		Rect(int width, int height){
			this->width=width;
			this->height=height;
		}
		friend bool RectManager :: equals(Rect r, Rect s);
};

int main(int argc, char** argv) {
	
	Rect a(3,4);
	Rect b(3,4);
	RectManager man;
	if(man.equals(a,b)) cout <<"equal" << endl;
	else cout <<"not equal" << endl;
	
	return 0;
}

 

프렌드 클래스 선언 

 

다른 클래스의 모든 멤버 함수를 클래스의 프렌드 함수로 한번에 선언할 수 있다 

 

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Rect;

class RectManager {
	public :
		bool equals(Rect r, Rect s);
		void copy(Rect& dest, Rect& src); 
};

class Rect{
	int width;
	int 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(int argc, char** argv) {
	
	Rect a(3,4);
	Rect b(5,6);
	RectManager man;
	
	man.copy(b,a); // a를 b에 복사한다  
	if(man.equals(a,b)) cout <<"equal" << endl;
	else cout <<"not equal" << endl;
	
	return 0;
}