📒 C++ - friend
📌 friend란?
- 함수나 클래스 선언 앞에 'friend' 예약어를 사용함으로써, 해당 함수, 또는 클래스가 접근 제한자의 영향을 받지 않도록 한다.
- friend가 선언된 클래스의 멤버가 아닌 함수 또는 클래스에 모든 멤버(friend가 선언된 클래스) 수준과 동일한 액세스 권한을 부여한다.
📌 friend 클래스 예시
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string _name;
friend class Person2;
public:
Person() : _name("liz")
{
}
};
class Person2
{
public:
void showName() const
{
Person p;
cout << p._name << endl;
}
};
int main()
{
Person2 p2;
p2.showName();
}
Output
liz
📌 friend 함수 예시
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string _name;
friend void showName();
public:
Person() : _name("liz")
{
}
};
void showName()
{
Person p;
cout << p._name << endl;
}
int main()
{
showName();
}
Output
liz