프랜드함수: 클래스 내에 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;
}
'언어 > C++' 카테고리의 다른 글
7장1번~4번 도서 관리 시스템 (연산자 중복) (0) | 2019.11.28 |
---|---|
책 제목 사전 순으로 비교하기 (0) | 2019.11.27 |
4장 예제- 면적 조건에 따른 원의 개수 구하기 (0) | 2019.11.22 |
6장 6번 - 정수 배열 합치기, 빼기 (0) | 2019.11.22 |
5장 예제- 복사 생성자 오빠 동생 복사 -깊은 복사 (0) | 2019.11.22 |