在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
代码示例如下:
#include <iostream> #include <string> int main() { using namespace std; cout<<"string类的六种构造方式:"<<endl; //0.创建一个长度为0的字符串 sting(); string zero; cout<<zero<<endl; //1. string(const char *s) string one("Lottery Winner"); cout<<one<<endl; //2.string(size_type,char c) string two(20,'s'); cout<<two<<endl; //3.string(const string & str,string size_type n = npos) //复制全部 string three(one); //位置从n = 7开始复制字符 cout<<three<<endl; string three1(one,7); cout<<three1<<endl; //重载操作符 += one += " Oops!"; cout<<one<<endl; //重载操作符 = two = "Sorry! That was"; three[0] = 'P'; string four; four = two + three; cout<<four<<endl; char alls[] = "All's well that ends well"; //4.string(const char *s,size_type n); //n在范围内 string five(alls,20); cout<<five<<endl; //n超出 string five1(alls,40); cout<<five1<<endl; //5.template<class Iter> string(Iter begin,Iter end) //这里Iter为char * string six(alls+6,alls+10); cout<<six<<endl; string seven(&five[6],&five[10]); cout<<seven<<"...\n"; return 0; }
输出如图:
参考书籍 C++ Primer Plus 第五版 中文版