類中的返回*this

這裏用move和set返回*this , 用display() 重載cout,

Code:
  1. #include<iostream>   
  2. #include<string>   
  3. using namespace std;   
  4. class Screen   
  5. {   
  6. public:   
  7.    typedef string::size_type index;   
  8.    Screen (index hght,index wdth,const string &cntnts);   
  9.    Screen& move(index r,index c);   
  10.    Screen& set(char);   
  11.    Screen& display(ostream &os);   
  12. private:   
  13.    string contents;   
  14.    index cursor;   
  15.    index height,width;   
  16. };   
  17. Screen::Screen (index hght,index wdth,const string &cntnts):contents(cntnts),cursor(0),height(hght),width(wdth)   
  18. {}   
  19. Screen& Screen::set(char c)   
  20. {   
  21. contents[cursor]=c;   
  22. return *this;   
  23. }   
  24. Screen& Screen::move(index r,index c)   
  25. {   
  26. index row=r*width;   
  27. cursor=row+c;   
  28. return *this;   
  29. }   
  30. Screen& Screen::display(ostream &os)   
  31. {   
  32. os<<contents;   
  33. return *this;   
  34. }   
  35. int main()   
  36. {   
  37. Screen myScreen(5,6,"aaaaa/naaaaa/naaaaa/naaaaa/naaaaa/naaaaa/n");   
  38. myScreen.move(4,0).set('#').display(cout);   
  39. cout<<endl;   
  40. myScreen.display(cout);   
  41. cout<<endl;   
  42. myScreen.move(1,0).set('%').display(cout);   
  43. return 0;   
  44. }  

 運行結果:

其中有幾個地方,沒有容錯處理……

想想在寫……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值