C++/따배C++ 08강 객체지향 기초
[C++/8.12] friend function and class
polarcompass
2021. 10. 26. 00:05
728x90
1. forward declaration 전방선언
#include<iostream>
using namespace std;
class B; // forward declaration (전방 선언)
class A
{
private:
int m_value = 1;
friend void doSomething(A &a, B &b);
};
class B
{
private:
int m_value = 2;
friend void doSomething(A &a, B &b);
};
void doSomething(A &a, B &b)
{
cout << a.m_value << " " << b.m_value << endl;
}
int main()
{
A a;
B b;
doSomething(a, b);
return 0;
}
2. member function 선선언 및 body 후 선언.
#include<iostream>
using namespace std;
class A; // forward declaration (전방 선언)
class B
{
private:
int m_value = 2;
public:
// 선 선언
void doSomething(A &a);
};
class A
{
private:
int m_value = 1;
friend void B::doSomething(A &a);
};
// body 후 선언
void B::doSomething(A &a)
{
cout << a.m_value << endl;
}
int main()
{
A a;
B b;
b.doSomething(a);
return 0;
}
728x90