C++primer 7.3.2节练习
练习7.27
头文件
1 #pragma once 2 class Screen { 3 typedef std::string::size_type pos; 4 public: 5 //构造函数 6 Screen() = default; 7 Screen(pos h, pos w) : height(h), width(w), contents(h * w, ' ') {}; 8 Screen(pos h, pos w, char c) : height(h), width(w), contents(h * w, c) {}; 9 Screen(std::string &s); 10 //成员函数 11 Screen &move(pos r, pos c); 12 Screen &set(pos r, pos c, char ch); 13 char getChar(pos x, pos y) const; 14 char getChar()const { 15 return contents[(x_axis - 1)*y_axis + x_axis]; 16 } 17 Screen &display(std::ostream &os) 18 { 19 os << contents; 20 return *this; 21 } 22 23 24 private: 25 std::string contents; 26 pos height = 0; 27 pos width = 0; 28 pos x_axis = 0; 29 pos y_axis = 0; 30 //void do_display(std::ostream &os) const { os << contents; } 31 };
源文件
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 system("pause"); 15 return 0; 16 } 17 18 Screen::Screen(string &s) 19 { 20 (*this).contents = s; 21 } 22 23 inline Screen & Screen::move(pos r, pos c) 24 { 25 x_axis = r; 26 y_axis = c; 27 return *this; 28 // TODO: 在此处插入 return 语句 29 } 30 31 inline Screen & Screen::set(pos r, pos c, char ch) 32 { 33 contents[(r - 1) * c + r] = ch; 34 return *this; 35 // TODO: 在此处插入 return 语句 36 } 37 38 inline char Screen::getChar(pos x, pos y) const 39 { 40 return contents[(x_axis - 1) * y_axis + x_axis]; 41 // TODO: 在此处插入 return 语句 42 }
练习7.28
如果是非引用版本,则程序返回的对象的临时副本,而不是对象的引用,这样只能改变的是临时副本的值,原本对象的值并没有改变,反映在上一题就是第一个调用改变了,而第二个display没有改变,另外需要说明的是如果只是改变display的类型,则在结果上并没有什么改变,只是最后输出的一个是对象自己,一个是对象的拷贝副本。
练习7.29
正确
练习7.30
一般使用到this,都是类的成员函数(非友元函数),可以对类中的成员随意访问。
其实使不使用this对编译器来说没什么影响,主要是程序员在维护代码上的代价。
优点是你通过this可以很容易通过IDE的智能感知功能来定位类的成员,
缺点是你应该为此程序的所有成员的引用都用this来是代码看起来一致。