[C++] 처음부터 시작하는 C++ 8편. friend 사용법

in #kr-dev6 years ago


안녕하세요!! @wonnieyoon입니다.

오늘 포스팅은 C++ "friend" 입니다.

friend

friend는 친구의 의미를 가지고 있습니다.
C++서 friend 또한 친구의 이미를 가진다고 생각하시면 됩니다.
친구란 가까운 사이죠?
클래스내에서 private 멤버는 외부에서 접근 할수 없습니다.
그러나 A,B 클래스가 있다고 가정했을때
A클래스 내에서 B클래스를 friend라고 지정하면
B클래스에서 A클래스의 private 멤버를 직접 접근이 가능합니다.
그러나 A에서 B클래스의 private 멤버는 접근 할수 없습니다.
그렇기 때문에 B에서도 A클래스를 friend로 해줘야지만
서로 접근 할수 있습니다.

형식

class A{
...
friend class B;
...
}

<코드>

class Test2;
class Test1{
private:
int num;
public:
Test1(int anum)
{
num = anum;
}
void GetInfo(Test2 t2);
friend class Test2;
};
class Test2{
private:
int num;
public:
Test2(int anum)
{
num = anum;
}
void GetInfo(Test1 t1);
friend class Test1;
};
void Test1::GetInfo(Test2 t2)
{
cout << t2.num << endl;
}

void Test2::GetInfo(Test1 t1)
{
cout << t1.num << endl;
}
int main()
{
Test1 t1(100);
Test2 t2(200);
t1.GetInfo(t2);
t2.GetInfo(t1);
return 0;
}

<결과>

먼저 코드를 보시면 class Test1을 만들기 전에
class Test2; 라고 적었습니다.
그 이유는 저렇게 선언해주지 않으면 컴파일러가
클래스를 찾지 못한다고 에러를 발생시킵니다.

클래스 Test1에서는 friend class Test2 를
클래스 Test2에서는 friend class Test1 을
선언했는데요.

그렇기 때문에 main에서 GetInfo함수에서
각각의 멤버변수를 호출할수 있는것입니다.

다만,friend를 사용하면 private 멤버에 직접 접근이 가능하지만
그만큼 직접 접근이 가능하기 때문에 조심해서 사용해야 합니다.


<목록>

1. [C++] 처음부터 시작하는 C++ 1편. 입출력
2. [C++] 처음부터 시작하는 C++ 2편. using,namespace 사용법
3. [C++] 처음부터 시작하는 C++ 3편. 메모리 할당 및 해제( new , delete ) 사용법
4. [C++] 처음부터 시작하는 C++ 4편. 구조체( struct) 사용법
5. [C++] 처음부터 시작하는 C++ 5편. 클래스 (Class) 사용법
6. [C++] 처음부터 시작하는 C++ 6편. 생성자 및 소멸자 사용법
7. [C++] 처음부터 시작하는 C++ 7편. Reference(참조자) 사용법

Sort:  

역시 끝내주는군요!! ㅋㅋㅋㅋ
나도 곧 써요!!

ㅎㅎ 즐거운 불금 보내세요~

짱짱맨 호출에 출동했습니다!!

Congratulations @wonnieyoon! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your Board of Honor.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

Do not miss the last announcement from @steemitboard!

Do you like SteemitBoard's project? Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.28
TRX 0.11
JST 0.031
BTC 68586.22
ETH 3911.83
USDT 1.00
SBD 3.63