练习7.32:
要想让clear函数作为Screen的友元,只需要在Screen类中做出友元声明即可。本题的真正关键之处是程序的组织结构,我们必须首先定义Window_mgr类,其中声明clear函数,但是不能定义它;接下来定义Screen类,并且在其中指明clear函数是其友元;最后定义clear函数。满足题意的程序如下所示:
#include <iostream>
#include <string>
using namespace std;class Window_mgr {public:void clear();
};class Screen {friend void Window_mgr::clear ();private:unsigned height = 0, width = 0;unsigned cursor = 0;string contents;public:Screen() = default;Screen(unsigned ht, unsigned wd, char c): height(ht), width(wd), contents(ht * wd, c) {};
};void Window_mgr::clear() {Screen myScreen(10, 20, 'X');cout << "清理之前myScreen的内容是:" << endl;cout << myScreen.contents << endl;myScreen.contents = "";cout << "清理之后myScreen的内容是:" << endl;cout << myScreen.contents << endl;
}int main() {Window_mgr w;w.clear();return 0;
}
测试结果: