c++primer第五版7.23题知识点

class screen {
public:
	typedef string::size_type pos;//定义类型成员(string::size_type类型见类下方注释),还可以使用using类型别名来定义using pos = string::size_type;
	screen() = default; //因为我们有定义构造函数,所以默认构造参数应该显示声明
	screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht*wd, c){}
	screen(pos ht, pos wd):height(ht), width(wd), contents(ht*wd,' '){}
	char get() const { return contents[cursor]; }//隐式内联
	inline char get(pos ht, pos wd) const;//显示内联
	screen &move(pos r, pos c);
private:
	pos cursor = 0;
	pos height = 0, width = 0;
	string contents;
};
/*
string::size_type类型
从逻辑上讲size()成员函数应该返回整形数值,但事实上返回的string::size_type类型的值。
我们需要对这种类型做一些解释。string类类型和许多其他库类型都定义了一些伙伴类型(companion types)。这些伙伴类型使得库类型的使用是机器无关的(machine-independent)。
size_type就是这些伙伴类型中的一种。它定义为与unsigned型(unsigned int或unsigned long)具有相同的含义,而且可以保证足够大可存储任意string对象的长度。
为了使用由string类型定义的size_type类型,程序员必须加上作用域操作符来说明所使用的size_type类型是由string类定义的。  
任何存储string的size操作结果的变量必须为string::size_type类型。特别重要的是,不要把size的返回值赋给一个int变量。
虽然我们不知道string::size_type的确切类型,但可以知道它是unsigned型(2.1.1节)。对于任意一种给定的数据类型,它的unsigned型所能表示的最大正数值比对应的signed要大一倍。
这个事实表明size_type存储的string长度是int所能存储的两倍。  
使用int变量的另一个问题是,有些机器上int变量的表示范围太小,甚至无法存储实际并不长的string对象。如在有16位int型的机器上,int类型变量最大只能表示32767个字符的string对象。
而能容纳一个文件内容的string对象轻易就会超过这个数字。因此,为了避免溢出,保存一个string对象size的最安全的方法就是使用标准库类型string:: size_type。
*/

猜你喜欢

转载自blog.csdn.net/TinnCHEN/article/details/86623581