C++ string类的构造函数

来源:互联网 发布:办公室暧昧 知乎 编辑:程序博客网 时间:2024/06/05 22:49
在c++中string类的构造函数有六种方式
分别是:
1.string(const char * s)
说明:将string对象初始化为s指向NBTS。NBTS为null-byte-temnated string的缩写,表示以空字符结束的字符串------传统的C字符串。
2.string(size_type n,char c)
说明:创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
3.string(const string & str,string size_type n = npos)
说明:将string对象初始化为对象str中从位置pos开始到结尾的字符,或从位置pos开始的n个字符
4.string()
说明:创建一个的string对象,长度为0
5.string(const char * s, size_type n)
说明:将string对象初始化为s指向的NBTS中的前n字符,即使超过了NBTS端
6.template<clas Iter> string(Iter begin,Iter end)
说明:将string对象初始化为区间[begin,end]内的字符,其中begin和end的行为就像指针,用于指定位置,范围包括begin在内,但不包括end



代码示例如下:

[cpp] view plain copy
 print?
  1. #include <iostream>  
  2. #include <string>  
  3.   
  4. int main()  
  5. {  
  6.     using namespace std;  
  7.     cout<<"string类的六种构造方式:"<<endl;  
  8.   
  9.     //0.创建一个长度为0的字符串 sting();  
  10.     string zero;  
  11.     cout<<zero<<endl;  
  12.   
  13.     //1. string(const char *s)  
  14.     string one("Lottery Winner");  
  15.     cout<<one<<endl;  
  16.   
  17.     //2.string(size_type,char c)  
  18.     string two(20,'s');  
  19.     cout<<two<<endl;  
  20.       
  21.     //3.string(const string & str,string size_type n = npos)  
  22.     //复制全部  
  23.     string three(one);   
  24.     //位置从n = 7开始复制字符  
  25.     cout<<three<<endl;  
  26.     string three1(one,7);  
  27.     cout<<three1<<endl;  
  28.   
  29.     //重载操作符 +=  
  30.     one += " Oops!";  
  31.     cout<<one<<endl;  
  32.   
  33.     //重载操作符 =  
  34.     two = "Sorry! That was";  
  35.     three[0] = 'P';  
  36.   
  37.     string four;  
  38.       
  39.     four = two + three;  
  40.     cout<<four<<endl;  
  41.   
  42.     char alls[] = "All's well that ends well";  
  43.     //4.string(const char *s,size_type n);  
  44.     //n在范围内  
  45.     string five(alls,20);  
  46.     cout<<five<<endl;  
  47.     //n超出  
  48.     string five1(alls,40);  
  49.     cout<<five1<<endl;  
  50.   
  51.     //5.template<class Iter> string(Iter begin,Iter end)  
  52.     //这里Iter为char *  
  53.     string six(alls+6,alls+10);  
  54.     cout<<six<<endl;  
  55.     string seven(&five[6],&five[10]);  
  56.     cout<<seven<<"...\n";  
  57.   
  58.     return 0;  
  59. }  
输出如图:

0 0
原创粉丝点击