歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ string到底是什麼?

C++ string到底是什麼?

日期:2017/3/1 9:29:47   编辑:Linux編程

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個章節中:

  1. Linux-C成長之路(一):Linux下C編程概要 http://www.linuxidc.com/Linux/2014-05/101242.htm
  2. Linux-C成長之路(二):基本數據類型 http://www.linuxidc.com/Linux/2014-05/101242p2.htm
  3. Linux-C成長之路(三):基本IO函數操作 http://www.linuxidc.com/Linux/2014-05/101242p3.htm
  4. Linux-C成長之路(四):運算符 http://www.linuxidc.com/Linux/2014-05/101242p4.htm
  5. Linux-C成長之路(五):控制流 http://www.linuxidc.com/Linux/2014-05/101242p5.htm
  6. Linux-C成長之路(六):函數要義 http://www.linuxidc.com/Linux/2014-05/101242p6.htm
  7. Linux-C成長之路(七):數組與指針 http://www.linuxidc.com/Linux/2014-05/101242p7.htm
  8. Linux-C成長之路(八):存儲類,動態內存 http://www.linuxidc.com/Linux/2014-05/101242p8.htm
  9. Linux-C成長之路(九):復合數據類型 http://www.linuxidc.com/Linux/2014-05/101242p9.htm
  10. Linux-C成長之路(十):其他高級議題

Copyright © Linux教程網 All Rights Reserved