#include <iostream>
#include <string>
using namespace std;
int main()
{
//关于string类的六个构造函数使用
string s1;//构造一个空字符串对象
string s2("hello world!");//传参构造
string s3(s2);//拷贝构造
string s4(s2, 2, 6);//Copies the portion of str that begins at the character position pos
//and spans len characters (or until the end of str, if either str is too short or if len is string::npos).
//上述是文档对于该构造函数的解释,从目标字符串对象的第pos个开始拷贝,直到拷贝外len个字符为止
// 如果其范围超出了目标字符串的范围,那么考到最后一个即可。
//如果第3个参数没给,从pos开始考npos个,npos被定义为static const size_t npos = -1;即无符号数的最大值
string s5("hello world", 5);//注意:第二个参数的类型需要是size_t的,即无符号整型
string s6(10, 'h');//构造n个相同字符的字符串
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
cout << s6 << endl;
return 0;
}
文档对这6个构造函数的描述如下:
大多数情况下:我们使用实例化一个string对象多数使用:无参构造,传参构造,拷贝构造,还有构造n个相同字符的字符串对象 这四个构造函数来构造对象。