C++ string到底是什么?要回答这个问题,先要了解什么是basic_string。
看一下basic_string的声明:template < class charT, //定义字符串中字符的类型
class traits = char_traits<charT>, // basic_string::traits_type
class Alloc = allocator<charT> // basic_string::allocator_type
> class basic_string;可见,basic_string实质上是一个类模板。
再解释的稍微详细一些:1.关于char_traits声明:template <class charT> struct char_traits;作用:Character traits classes specify character properties and provide specific semantics for certain operations on characters and sequences of characters.(来自C++ Referencce,地址:http://www.cplusplus.com/reference/string/char_traits/)即:它指定了字符的属性,并且提供了作用在字符或字符序列上的某些操作的特定语义。2.关于allocator声明:template <class T> class allocator;//<memory>头文件下 allocator:分配器作用:
Allocators are classes that define memory models to be used by some parts of the Standard Library, and most specifically, by STL containers.(来自C++ Referencce,地址:http://www.cplusplus.com/reference/memory/allocator/?kw=allocator)
即:它定义了用于标准库的部分内容,特别是STL的内存模型。现在我们来看string的声明:typedef basic_string<char, char_traits<char>, allocator<char>> string;现在,我们明白了,原来是这么回事:用基本类型char实例化类模板basic_string,得到一个具体的模板类,然后,将其typedef为string。换句话说,string本质上是一个模板类,就是basic_string<char, char_traits<char>, allocator<char>>,string是对应的“简称”。 直观地理解,string的实例对象(就是说 string str;中的str)是一个char序列,但不同于char* str,stingr str带有许多封装好的针对自己的操作。ps:basic_string还有其它实例,比如说:typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t>> wstring;------------------------------分割线------------------------------
C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码 http://www.linuxidc.com/Linux/2014-05/101227.htm读C++ Primer 之构造函数陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm读C++ Primer 之智能指针 http://www.linuxidc.com/Linux/2011-08/40177.htm读C++ Primer 之句柄类 http://www.linuxidc.com/Linux/2011-08/40175.htm
将C语言梳理一下,分布在以下10个章节中:- Linux-C成长之路(一):Linux下C编程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
- Linux-C成长之路(二):基本数据类型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
- Linux-C成长之路(三):基本IO函数操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
- Linux-C成长之路(四):运算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
- Linux-C成长之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
- Linux-C成长之路(六):函数要义 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
- Linux-C成长之路(七):数组与指针 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
- Linux-C成长之路(八):存储类,动态内存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
- Linux-C成长之路(九):复合数据类型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
- Linux-C成长之路(十):其他高级议题
本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-05/116871.htm