string类对+= 和=的重载
string 重载了+=运算符可以接受string ,c风格字符串,单个字符
string one;
string two("two");
//string对+=的三种重载可以接受string类,c风格字符串,单个字符
one += "1";//接受c风格字符串
cout << one << endl;//1
one += two;//接受string类
cout << one << endl;//1two
one += '1';//接受单个字符可用push_back
cout << one << endl;//1two1
以上三种都是合法的,也就是说+=后面三中数据元素都可以接收
同时=号上面三种数据元素也都合法
one = "1";//接受c风格字符串
cout << one << endl;//1
one = two;//接受string类
cout << one << endl;//two
one = '1'; //接受单个字符
cout << one << endl;//1
string对+的重载
本质时string.oprator(elment)
相当于一个string类调用了加函数,之后返回一个string临时对象,再将临时对象赋值给另一个
string
string one;
string two("two");
//string对+的三种重载可以接受string类,c风格字符串,单个字符
one = two + "1";//接收c风格字符串
cout << one << endl;//two1
one = two + two;//j接受string类
cout << one << endl;//twotwo
one = two + '1';//接受单个字符
cout << one << endl;//two1
由于对函数重载没有交换律,所以加号左边必须是string类作为调用主体不能交换顺序
但是string应该是提供了友元函数重载
one = '1' + two;
cout << one << endl;//1two
one = "1"+ two;
cout << one << endl;//1two
这两种也是对的
string str="1"+'1'这种就是错的,加号两侧都没有string类相当于没调用string的重载,至于C风格字符串是否有重载我不太清楚可以include《cstring》看一下,直接用双引号的是c风格字符串
string构造函数
标准STL 提供了多种构造函数
string str1 = "two";
string str(str1);//使用string类构造
cout << str << endl;//two
string str2("two");//使用C风格字符串构造
cout << str2 << endl;//two
string str3(5, '1');//构造由n个字符组成的字符串
cout << str3 << endl;//11111
string str4("21111", 3);//构造C风格字符串前n个字符
cout << str4 << endl;//211
//可以超过字符串本身长度
string str5("11111", 7);//超过部分填充非法内存字符
cout << str5 <<" "<<str5.length()<<" "<<str5[6]<< endl;//11111
string str6("1234", 3, 1);//从第三个字符开始读一个
cout << str6 << endl;
//长度参数可以超出范围,但是长度超出范围不会补空
//位置参数不能超过主串长度
string str7("1234", 4, 6);//从第四个字符开始读0个
cout << str7 << " " << str7.length() << endl;// 0
string str8("1234", 3, 6);//从第三个字符开始读一个
cout << str8 << " " << str8.length() << endl;// 1
string str9 = "1234";
string str10(str9, 2);//构造string类第n个字符后的子串
cout << str10 << endl;//34
//位置参数不可以超范围但可以是主串长度,此时子串长度为0
string str11(str9, 4);//构造string类第n个字符后的子串
cout << str11.length() << endl;//0
string str12(str9, 2, 1);//从位置2开始读一个
cout << str12 << endl;
//位置参数不能超过主串长度,长度参数可以超,超i过不补空
string str13(str9, 2, 10);//从位置2开始读一个
cout << str13 <<" "<<str13.length()<< endl;
//初始区间[begin,end)内容
char str14[] = "1234";
string str15(str14 + 2, str14 + 5);//超范围补空
cout << str15 <<endl<<str15.length()<< endl;
string str16(&str9[0] , &str9[2]);
cout << str16 << endl << str16.length() << endl;
说一下几种特殊的构造
长度自动补齐的构造
1.string str(chars("..."),length n)
构造c风格字符串前n个长度的子串,长度无限制
2.template <class iter>
string str(iter begin,iter end)
注意区间为[begin,end),左闭右开
使用指针形式可以超长,角标形式不能非法访问
两种方式都会访问非法内存
一般构造,带位置长度参数
1。string str( chars("...")/string,pos,length)
位置参数不能越界,相当于提前声明了str最大长度为主串长度-pos,所以长度参数越界也无所谓,不会补空
2.string str(string,pos)
与同样格式的C风格字符串构造不同,是读pos后所有内容
不能越界,相当于提前声明了str最大长度为主串长度-pos