您的位置:首页 > 编程语言 > C语言/C++

C++Primer第五版 7.4节练习

2015-09-16 07:20 337 查看
练习7.33:如果我们给Screen添加一个如下所示的size成员将发生什么情况?如果出现了问题,请尝试修改它。

pos Screen::size() const

{

return height * width;

}

在类里:

Public:

pos size() const;

类体外:

Screen::pos Screen::size() const

{

return height * width;

}

见云盘程序:练习7.33.cpp

练习7.33

/*
*练习7.33
*2015/7/14
*问题描述:练习7.33:如果我们给Screen添加一个如下所示的size成员将发生什么情况?如果出现了问题,请尝试修改它。
   pos Screen::size() const
{
    return height * width;
}

*功能:修改 
*作者:Nick Feng 
*邮箱:nickgreen23@163.com 
* 
*/

#include <iostream> 
#include <string>
#include <vector> 
using namespace std;

class Screen{
public:

    typedef std::string::size_type pos;
    Screen() = default;
    Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * wd, c){}
    char get() const { return contents[cursor]; }
    inline char get(pos ht, pos wd) const;
    Screen &move(pos r, pos c);
    Screen &set(char);
    Screen &set(pos, pos, char);
    Screen &display(std::ostream &os)
            {
                do_display(os);
                return *this;
            }
    const Screen &display(std::ostream &os) const
            {
                do_display(os);
                return *this;
            }
        //extern void Window_mgr::clear(ScreenIndex);   
    //friend void Window_mgr::clear(ScreenIndex);

    //friend void Window_mgr::clear(ScreenIndex);
    //extern class Window_mgr;
    //friend class Window_mgr;
    //extern void Window_mgr::clear(ScreenIndex);
    pos size() const;
private:
    pos cursor = 0;
    pos height = 0, width = 0;
    std::string contents;
    void do_display(std::ostream &os) const { os << contents;}
};

inline 
Screen &Screen::move(pos r, pos c)
{
    pos row = r * width;
    cursor = row + c;
    return *this;
}

char Screen::get(pos r, pos c) const
{
    pos row = r * width;
    return contents[row + c];
}

inline Screen &Screen::set(char c)
{
    contents[cursor] = c;
    return *this;
}

inline Screen &Screen::set(pos r, pos col, char ch)
{
    contents[r * width + col] = ch;
    return *this;
}

Screen::pos Screen::size() const
{
    return height * width;
}
int main()
{
    Screen test(5,5,'x');
    test.display(cout) ;
    cout << endl;
    cout << test.size() << endl;
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: