string类的6个构造函数

#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;
}

634b6e09b8a04a31b6316c3ca9874536.png

文档对这6个构造函数的描述如下:

116d4ef33ed847e784ced4922ff231b8.png

大多数情况下:我们使用实例化一个string对象多数使用:无参构造,传参构造,拷贝构造,还有构造n个相同字符的字符串对象 这四个构造函数来构造对象。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值