Notice
Recent Posts
250x250
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
관리 메뉴

일상 코딩

[C++/8.12] friend function and class 본문

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