问题描述
我一直在尝试一些例子(C ++ Primer by Stanley Lippman)
,我明白一个类可以让另一个类成为其朋友(访问一些私有成员)。现在我正在阅读一个成员函数是一个朋友,我尝试这个例子
I've been trying some examples in a book (C++ Primer by Stanley Lippman)and I understand that a class can make another class its friend (to access some private members). Now I'm reading about a member function being a friend and I try the example
class Screen
{
public:
friend void Window_mgr::clear();
typedef std::string::size_type pos;
Screen () = default;
Screen (pos ht, pos wd, char c) : height (ht), width (wd),
contents (ht * wd, c) { }
private:
void do_display (std::ostream &os) const
{
os << contents;
}
pos cursor = 0;
pos height = 0, width = 0;
pos test_num = 100, test_num2 = 222;;
std::string contents = "contents";
};
class Window_mgr {
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear (ScreenIndex);
private:
std::vector <Screen> screens {Screen (24, 80, ' ')};
};
void Window_mgr::clear(ScreenIndex i)
{
Screen &s = screens[i];
s.contents = std::string(s.height * s.width, ' ');
}
但会产生编译器错误,说
but it produces a compiler error saying
,然后我阅读:
•接下来,定义Screen屏幕,包括一个明确的朋友声明。
• Next, define class Screen, including a friend declaration for clear.
•最后,定义清除,现在可以在屏幕中引用成员。
• Finally, define clear, which can now refer to the members in Screen.
我不明白这部分 - 有人可以解释吗?
I don't understand this part -- can someone explain?
推荐答案
当编译器获得 friend void Window_mgr :: clear();
它不知道 Window_mgr
是什么,因为它还没有看到。你需要重新排序一些东西让它工作。首先你转发声明屏幕
,然后你有 Window_mgr
When the compiler gets to friend void Window_mgr::clear();
it has no idea what Window_mgr
is as it has not seen that yet. You need to reorder things around a little to get this to work. first you forward declare Screen
and then you have you Window_mgr
class Screen;
class Window_mgr {
public:
using ScreenIndex = std::vector<Screen>::size_type;
void clear(ScreenIndex);
Window_mgr();
private:
std::vector <Screen> screens; // don't initialize here as we don't know what a screen actually is yet
//std::vector <Screen> screens {Screen (24, 80, ' ')}; can't do this as we don't what a Screen is here
};
然后你可以让你 Screen
class
Then you can have you Screen
class
class Screen
{
public:
friend void Window_mgr::clear(ScreenIndex);
typedef std::string::size_type pos;
Screen() = default;
Screen(pos ht, pos wd, char c) : height(ht), width(wd),
contents(ht * wd, c) { }
private:
void do_display(std::ostream &os) const
{
os << contents;
}
pos cursor = 0;
pos height = 0, width = 0;
pos test_num = 100, test_num2 = 222;
std::string contents = "contents";
};
然后你可以拥有 Window_mgr
使用屏幕
Window_mgr::Window_mgr() : screens{ Screen(24, 80, ' ') } {}
void Window_mgr::clear(ScreenIndex i)
{
Screen &s = screens[i];
s.contents = std::string(s.height * s.width, ' ');
}
你可以看到它在这
这篇关于会员功能朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!