【发布时间】:2015-09-29 07:48:07
【问题描述】:
我一直在尝试书中的一些示例(Stanley Lippman 的 C++ Primer) 我知道一个类可以让另一个类成为它的朋友(访问一些私有成员)。现在我正在阅读有关成员函数是朋友的信息,我尝试了这个例子
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, ' ');
}
但它会产生编译器错误提示
Window_mgr 尚未声明
然后我读到了这个:
• 首先,定义Window_mgr 类,它声明但不能定义clear。必须先声明 Screen,clear 才能使用 Screen 的成员。
• 接下来,定义类 Screen,包括一个用于 clear 的朋友声明。
• 最后,定义 clear,它现在可以引用 Screen 中的成员。
我不明白这部分 - 谁能解释一下?
【问题讨论】: