首页 > 代码库 > C++primer 7.3.4节练习

C++primer 7.3.4节练习

练习7.32

头文件

 1 #pragma once
 2 #include <vector>
 3 
 4 
 5 class Screen {
 6     friend class Window_mgr;
 7     typedef std::string::size_type pos;
 8 public:
 9     //构造函数
10     Screen() = default;
11     Screen(pos h, pos w) : height(h), width(w), contents(h * w,  ) {};
12     Screen(pos h, pos w, char c) : height(h), width(w), contents(h * w, c) {};
13     Screen(std::string &s);
14     //成员函数
15     Screen &move(pos r, pos c);
16     Screen &set(pos r, pos c, char ch);
17     char getChar(pos x, pos y) const;
18     char getChar()const {
19         return contents[(x_axis - 1)*y_axis + x_axis];
20     }
21     Screen &display(std::ostream &os)
22     {
23         os << contents;
24         return *this;
25     }
26 
27 
28 private:
29     std::string contents;
30     pos height = 0;
31     pos width = 0;
32     pos x_axis = 0;
33     pos y_axis = 0;
34     //void do_display(std::ostream &os) const { os << contents; }
35 };
36 
37 class Window_mgr {
38 public:
39     void clear(int i);
40 private:
41     std::vector<Screen> screens{ Screen(3,4,#) };
42 };

 

源文件

 1 #include <iostream>
 2 #include <string>
 3 #include "screen.h"
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     Screen myScreen(5, 5, X);
10     myScreen.move(4, 0).set(3, 4, #).display(cout);
11     cout << "\n";
12     myScreen.display(cout);
13     cout << "\n";
14     Window_mgr w1;
15     w1.clear(0);
16     system("pause");
17     return 0;
18 }
19 
20 Screen::Screen(string &s)
21 {
22     (*this).contents = s;
23 }
24 
25 inline Screen &Screen::move(pos r, pos c)
26 {
27     x_axis = r;
28     y_axis = c;
29     return *this;
30     // TODO: 在此处插入 return 语句
31 }
32 
33 inline Screen &Screen::set(pos r, pos c, char ch)
34 {
35     contents[(r - 1) * c + r] = ch;
36     return *this;
37     // TODO: 在此处插入 return 语句
38 }
39 
40 inline  char Screen::getChar(pos x, pos y) const
41 {
42     return contents[(x_axis - 1) * y_axis + x_axis];
43     // TODO: 在此处插入 return 语句
44 }
45 
46 void Window_mgr::clear(int i)
47 {
48     Screen &s = screens[i];
49     s.contents = string(s.height * s.width,  );
50 }

其实这里是有问题的,问题在于如果使用window_mgr类的成员函数作为Screen类的友元,在定义顺序完全正确的情况下,由于在window_mgr内需要使用到Screen类型,但是此时并没有对Screen类进行声明定义,所以会发生错误,以当前的知识储备还不能解决之一问题,需要更多的学习

C++primer 7.3.4节练习