프로그래밍 언어/C++
C++ 친구 클래스 및 함수 (friend)
ShovelingLife
2022. 7. 20. 19:38
friend 클래스는 friend로 선언된 다른 클래스의 private 및 protected 멤버에 접근할 수 있다. 사용법은 friend 키워드를 사용하여 클래스나 함수를 명시 해 주는 것이다. 함수 같은 경우에는 전역함수랑 동일해진다, static 클래스 종속 함수랑은 별개.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class A
{
friend class B;
int mVal = 0;
protected:
void ProtectedFunc() { cout << "A class ProtectedFunc" << endl; }
friend void FriendFunc(A& a)
{
cout << "A class FriendFunc ";
a.mVal += 20;
a.PrintVal();
}
public:
int Get() const { return mVal; }
void Set(int Val)
{
cout << "A class Set mVal : ";
this->mVal = Val;
PrintVal();
}
void PrintVal() { cout << mVal << endl; }
};
class B
{
public:
void Run(A& a) { a.ProtectedFunc(); }
void Test(A& a)
{
a.mVal += 10;
cout << "B class Test ";
a.PrintVal();
}
};
int main()
{
A a;
B b;
b.Run(a);
FriendFunc(a);
a.Set(10);
b.Test(a);
}