C++ String类构造函数

构造函数描述
string(const char*)将string对象初始化为s指向的NBTS(null-terminated string)即以空字符结束的传统C字符串
string(size_type n,char c)创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
string(const string &str)将一个string对象初始化为string对象str(复制构造函数)
string()创建一个默认的string对象,长度为0
string(const char *s,size_type n)将string对象初始化为s指向的NBTS的前n个字符,即使超过了NBTS的结尾

template<class Iter>

string(Iter begin,Iter end)

将string对象初始化为区间为区间[begin,end]内的字符,其中begin和end的行为就像指针,用于指定位置,范围包括begin在内,但不包括end
string(const string &str,size_type pos,size_type n =npos)将一个string对象初始化为对象str中从位置pos开始到结尾的字符,或从位置pos开始的n个字符
string(string &&str)noexcept这是C++11新增的,它将一个string对象初始化为string对象str,并可能修改str(移动构造函数)
string(initializer_list<char> il)这是C++11新增的,它将一个string渡西iang初始化为初始列表il中的字符

将代码与输出贴在下边,

1.注意4使用了运算符重载.

2.第七个的第一个参数应该是const string &str,但是这里使用了char[],是自动进行了类型转换。

3.第六个,对于iter begin,iter end,这两个参数来说,可以直接用&给出地址,也可以使用数组名代表地址。但是不能用对象名,比如string seven(five+6,five+10).因为对象名不被看作对象的地址,与数组不一样。

#include <iostream>
#include <string>
using namespace std;
void test_string();
int main() {
    test_string();
    return 0;
}

void test_string()
{
    //1.
    string one("aa");
    cout<<"one is "<<one<<endl;

    //2.
    string two(4,'b');
    cout<<"two is "<<two<<endl;

    //3.
    string three(one);
    cout<<"three is "<<three<<endl;

    //4.
    string four;
    four = two + three;// attention    operater+()
    cout<<"four is "<<four<<endl;

    //5.
    string five("Welcome dd",7);
    cout<<"five is "<<five<<endl;

    //6.
    //string six(&two[1],&two[3]);
    //cout<<"six is "<<six<<endl;

    char arr[]="what did i write";
    string six(arr,arr+8);
    cout<<"six is "<<six<<endl;

    //7.
    string seven(arr,1,3);//convert
    cout<<"seven is "<<seven<<endl;
    
}


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值