C++primer 7.3.4節練習

來源:互聯網
上載者:User

標籤:return   getc   getchar   ++   width   需要   成員   c++   學習   

練習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) const41 {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節練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.