Why can't I declare a friend in one class that is a private member of another class?

Given the following code:

class Screen;

class WindowMgr
{
    WindowMgr& relocateScreen( int r, int c, Screen& s);
};

class Screen
{
    friend WindowMgr& WindowMgr::relocateScreen( int r, int c, Screen& s);
    // ^ cannot access private member declared in class 'WindowMgr'

    int m_nR,
        m_nC;
};

WindowMgr& WindowMgr::relocateScreen( int r, int c, Screen& s)
{
    s.m_nR = r;
    s.m_nC = c;
    return *this;
}

Why Screendoesn't the class declare a member function WindowMgr::relocateScreenas a friend? Screendoes not want to use this private member function of another class, but simply wants this function to have access to its own private members.

Creating a public function relocateScreencan be a bad design if it is intended only for use in a class WindowMgr. Likewise, making a Screenfriend WindowMgrcan be a bad design if it is not designed to access private members WindowMgrin any other way.

Where am I wrong here? What is the right approach? Am I really fooling myself?

+3
4

, WindowMgr::relocateScreen() WindowMgr.

++ 11.4-7:

", , ..."

relocateScreen() - Screen WindowMgr a friend of Screen. , WindowMgr relocateScreen() Screen - Screen.

+1

WindowMgr . .

0

WindowMgr:: relocateScreen , , WindowMgrFoo 1 relocateScreen. Delcare WindowMgrFoo WindowMgr WindowMgrFoo? WindowMgr WindowMgrFoo, , .

0

- . , :

WindowMgr::relocateScreen, Screen, Screen WindowMgr. /.

In order not to violate the principles of OOD, only public class member functions can be declared by friends in another, because otherwise the latter becomes dependent on the private implementation of the former.

0
source

Source: https://habr.com/ru/post/1755848/


All Articles