lantionzy

coding
posts - 10, comments - 39, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

C++ string::size_type 类型

Posted on 2009-10-22 09:10 lantionzy 阅读(12040) 评论(8)  编辑 收藏 引用 所属分类: C++ Primer
int main()
{
    
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 类定义。任何存储stringsize操作结果的变量必须为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
string str("some string");
for (string::size_type index = 0; index != str.size(); ++index)
    cout 
<< str[index] << endl;


转到博客首页查看更多随笔

Feedback

# re: C++ string::size_type 类型  回复  更多评论   

2009-10-22 12:12 by Vincent
隐约记得象这样的类型有很多..貌似是为了可移植

# re: C++ string::size_type 类型[未登录]  回复  更多评论   

2009-10-22 18:43 by A
请问这里面讨论了什么问题

# re: C++ string::size_type 类型  回复  更多评论   

2009-10-22 22:43 by ddlau
what's the point?

# re: C++ string::size_type 类型[未登录]  回复  更多评论   

2009-10-23 09:11 by yuhuan
这个文章介绍了编程习惯和风格,不限于技术细节而从全局着手,是好文章.

# re: C++ string::size_type 类型  回复  更多评论   

2009-10-23 11:29 by bin89913
这不是C++ primer上的原话嘛

# re: C++ string::size_type 类型  回复  更多评论   

2009-10-26 14:56 by 欣萌
复习一次 真的挺好的。
有时候 我图方便就int 了
其实这样挺不好的。

# re: C++ string::size_type 类型  回复  更多评论   

2009-10-28 20:20 by Rye
用<stdint.h>

# re: C++ string::size_type 类型  回复  更多评论   

2012-11-17 11:09 by Your Uncle
抄袭C++ Primer

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理