习题7-21-习题7-22
这个看你需要设置,只要记住两个知识点:
1、struct与class默认权限不同;
2、private数据成员一般只能由类的函数访问,外部函数无法访问;public数据成员则都可以访问;
习题7-23-习题7-24
class Screen {
public:
typedef std::string::size_type pos;
Screen() = default;
Screen(pos ht,pos wd,char c):height(ht),width(wd),contents(' '){}
Screen(pos ht,pos wd,char c):height(ht),width(wd),contents(ht*wd,c){}
char get()const
{
return contents[cursor];
}
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
};
习题7-25
P239页 7.1.5 能安全的使用拷贝和赋值操作,但是不能分配内存;
习题7-26
inline double avg_price() const { return units_sold ? revenue/units_sold : 0; }
习题7-27
#include <iostream>
#include<string>
using namespace std;
class Screen {
public:
typedef std::string::size_type pos;
Screen() = default;
Screen(pos ht, pos wd) :height(ht), width(wd), contents(ht*wd, ' ') {}
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;
}
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;
}
void main()
{
Screen myScreen(5, 5, 'X');
myScreen.move(4, 0).set('#').display(cout);
cout << "\n";
myScreen.display(cout);
cout << "\n";
}
习题7-28
由于使用的事类的副本,所以不会改变原来的类,第二行作用在副本上;
习题7-29
输出为:
引用输出:
XXXXX XXXXX XXXXX XXXXX #XXXX
XXXXX XXXXX XXXXX XXXXX #XXXX
非引用输出:
XXXXX XXXXX XXXXX XXXXX #XXXX
XXXXX XXXXX XXXXX XXXXX XXXXX
习题7-30
这个是照着答案抄的。。。
优点:
1、使程序意图明确,更易读;
2、可以使形参名和要赋值的成员名相同。
如:std::string& setName(const string& name) { this->name = name; }
缺点:有些场景下比较多余
std::string const& getName() const { return this->name; }