{
string str( " Hello World!/n " );
cout << " The size of " << str << " is " << str.size()
<< " characters, including the newline " << endl;
return 0 ;
}
从逻辑上来讲, size () 成员函数似乎应该返回整形数值,或是无符号整数。但事实上, size 操作返回的是 string::size_type 类型的值。
string 类类型和许多其他库类型都定义了一些配套类型( companion type)。通过这些配套类型,库类型的使用就能与机器无关( machine-independent)。 size_type 就是这些配套类型中的一种。它定义为与 unsigned 型( unsigned int 或 unsigned long )具有相同的含义,而且可以保证足够大能够存储任意 string 对象的长度。为了使用由 string 类型定义的 size_type 类型是由 string 类定义。任何存储 string 的 size 操作结果的变量必须为 string::size_type 类型。特别重要的是,不要把 size 的返回值赋给一个 int 变量。
虽然我们不知道 string::size_type 的确切类型,但可以知道它是 unsigned 型。对于任意一种给定的数据类型,它的 unsigned 型所能表示的最大正数值比对应的 signed 型要大一倍。这个事实表明 size_type 存储的 string 长度是 int 所能存储的两倍。
使用 int 变量的另一个问题是,有些机器上 int 变量的表示范围太小,甚至无法存储实际并不长的 string 对象。如在有 16 位 int 型的机器上, int 类型变量最大只能表示 32767 个字符的 string 对象。而能容纳一个文件内容的 string 对象轻易就会超过这个数字。因此,为了避免溢出,保存一个 stirng 对象 size 的最安全的方法就是使用标准库类型 string::size_type 。
for ( string ::size_type index = 0 ; index != str.size(); ++ index)
cout << str[index] << endl;