C++/Friend Relationship
C++ Friend Relationship
Soul-Learner
2016. 12. 24. 13:31
C++ 프로그래밍, 친구관계 ( Friend Relationship )
friend 키워드를 이용하여 친구 설정하기
클래스의 멤버변수나 멤버함수는 private, protected 를 이용하여 외부에서 직접 접근이 안되도록 설정할 수가 있다. 그러나 이 클래스와 친구관계에 있는 외부의 함수나 클래스는 접근이 허용된다. 어떤 클래스와 친구관계가 성립되기 위해서는 접근을 허용하는 클래스에 friend 라는 키워드를 이용하여 외부함수의 원형이나 다른 클래스를 선언해야 한다.
A 클래스가 B 클래스를 친구로 등록했다면 B에서 A의 private, protected 멤버에 접근이 가능하지만 그 반대는 안된다. 즉, A 클래스에서 B의 private, protected 멤버에는 접근할 수 없다.
친구의 친구와는 친구관계가 성립되지 않으므로 필요하다면 직접 친구관계를 설정해야 한다
friend 함수, friend 클래스를 사용한 예
#include <iostream> #include <locale> #include <string> using namespace std; class CBoard { int num; wstring title; wstring contents; wstring author; friend class CView; // 다른 클래스를 친구로 설정함 public: CBoard(){ wprintf(L"CBoard 기본 생성자 \n"); } CBoard(int, wstring, wstring, wstring); }; class CView { public: void printBoard(CBoard&); void printBdList(CBoard[], int); }; class CCont { //CBoard 기본생성자를 이용하여 배열의 원소가 초기화됨 CBoard bdList[5]; // CBoard 클래스에 기본 생성자가 없으면 오류발생 CView view; public: // 전역함수를 친구로 설정하여 bdList 멤버 변수를 초기화하도록 함 friend void init(CCont&); // 전역함수를 친구로 설정함 CCont(){ init(*this); } // *this: 현재 객체의 주소로부터 값(객체)을 추출하여 전달함 void showList(){ view.printBdList(bdList,5); } }; CBoard::CBoard(int num, wstring title, wstring contents, wstring author){ this->num = num; this->title = title; this->contents = contents; this->author = author; } void CView::printBoard(CBoard& b){ wcout << L"게시판 글 읽기" << endl; wcout << "-----------------------------------" << endl; wcout << L"번호\t제목\t작성자" << endl; wcout << b.num << "\t" << b.title << "\t" << b.author << endl; wcout << "-----------------------------------" << endl; } void CView::printBdList(CBoard b[], int len){ wcout << L"==== 게시판 글 리스트 ====" << endl; wcout << L"번호\t" << L"제 목\t" << L"작성자" << endl; wcout << "----------------------" << endl; for(int i=0;i<len;i++) { wcout << b[i].num << "\t" << b[i].title << "\t" << b[i].author << endl; } wcout << L"======================" << endl; } // 전역함수. CCont 클래스에 friend로 등록되어 있으므로 private 멤버에 접근 가능 void init(CCont& cont){ cont.bdList[0] = CBoard(11, L"헬로", L"게시판 시작했어요 ^^", L"김인철"); cont.bdList[1] = CBoard(12, L"c++", L"좀 어렵군요 ^^", L"박찬호"); cont.bdList[2] = CBoard(13, L"생성자", L"객체 생성시 자동 실행", L"김연아"); cont.bdList[3] = CBoard(14, L"static", L"자동으로 한번만 생성", L"박지성"); cont.bdList[4] = CBoard(15, L"friend", L"private 멤버에 접근가능", L"권영순"); } int main() { setlocale(LC_ALL, ""); wcout << L"프렌드 함수와 프렌트 클래스" << endl; CCont cont; cont.showList(); return 0; }