- friend 함수예제
// friend 함수의 예
#include<iostream>
using namespace std;
 class myclass {
 int n, d;
public:
 myclass(int i, int j) { n = i; d = j; }
 // myclass의 friend를 선언한다.
 friend int isfactor(myclass ob);
};
/* 다음은 friend 함수의 정의. 이것은 d가 n의 인
수이면 참을 반환한다. 키워드 friend가
isfactor()의 정의에서는 사용되지 않는다는
점에 유의하세요. */
int isfactor(myclass ob) {
 if (!(ob.n % ob.d)) return 1;
 else return 0;
}
int main() {
 myclass ob1(10, 2), ob2(13, 3);
 if (isfactor(ob1)) cout << "2 is a factor of10\n";
 else cout << "2 is not a factor of 10\n";
 if (isfactor(ob2)) cout << "3 is a factor of 13\n";
 else cout << "3 is not a factor of 13\n";
 return 0;
}

- 위에서처럼 friend 함수는 객체의 멤버함수가 아니고 전역함수이다.
  단지 해당 객체의 private 속성의 멤버변수를 얻어낼수 있게 하기위해 지정하는것이다.
- friend 는 클래스로도 가능하고 어떤 클래스의 멤버함수로도 가능하다



실습문제 : 연습문제 5-1, 연습문제 5-5, 연습문제 5-8
일반과제 : 실습문제(은행계좌 Ver2)

'2007년1학기 > C++프로그래밍' 카테고리의 다른 글

C++ 강의노트 5,6장  (22) 2007.04.24
C++ 6강 강의자료  (24) 2007.04.11
C++ 프로그래밍4강  (43) 2007.03.28
C++ 에서 달라진점  (21) 2007.03.21
C++ 강의노트 3장  (40) 2007.03.21
by cranix 2007. 4. 4. 13:59
| 1 |