私人功能作为其他班级的朋友

Guc*_*112 5 c++ encapsulation class friend

我有一个用C++编写的以下代码:

#include <iostream>

using namespace std;

class Window;
class Level
{
    int level;
    int get(Window& w);
public:
    Level(void): level(3) {}
    void show(Window& w);
};

void Level::show(Window& w)
{
    cout << get(w) << endl;
}

class Item
{
    static const int item = 8;
};

class Window
{
    friend int Level::get(Window& w);
    int window;
public:
    Window(void): window(2) {}
    void show(void);
};

void Window::show(void)
{
    cout << "window" << endl;
}

int Level::get(Window& w)
{
    return w.window + level;
}

int main()
{
    Window wnd;
    Level lvl;
    wnd.show();
    lvl.show(wnd);
    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我想访问Window只能通过友元函数访问的类的私有成员get,这也是类的私有函数Level.当我正在尝试编译时,我遇到了错误C2248.是否可以将私人功能作为其他班级的朋友?

小智 1

好友声明名称必须可访问吗?引用标准措辞“由友元声明指定的名称应在包含友元声明的类的范围内可访问”,并给出了该(看起来有点奇怪)规则存在的理由。