[1] string基础
[1.1] string 的构造
![]()
1 #include <iostream>
2 #include <string>
3
4 int main()
5 {
6 using namespace std;
7
8 cout << "1 --- string(const char* s):将string对象初始化为s指向的C风格字符串" << endl;
9 string one("benxintuzi_1");
10 cout << "one = " << one << endl; // 重载了 <<
11
12 cout << "2 --- string(size_type n, char c):以字符c初始化包含n个字符的string对象" << endl;
13 string two(20, '$');
14 cout << "two = " << two << endl;
15
16 cout << "3 --- string(const string& str):复制构造函数初始化" << endl;
17 string three(one);
18 cout << "three = " << three << endl;
19
20 cout << "4 --- string():默认构造函数" << endl;
21 string four;
22 four += one; // 重载了 +=
23 four = two + three; // 重载了 +
24 cout << "four = " << four << endl;
25
26 cout << "5 --- string(const char* s, size_type n):用s指向的C风格字符串的前n个字符初始化string对象" << endl;
27 char s[] = "benxintuzi";
28 string five(s, 5);
29 cout << "five = " << five << endl;
30
31 cout << "6 --- string(Iter begin, Iter end):用[begin, end)区间内的字符初始化string对象" << endl;
32 string six(s + 2, s + 5);
33 cout << "six = " << six << endl;
34
35 cout << "7 --- string(const string& str, string size_type pos = 0, size_type n = npos):将string对象初始化为str中从pos开始的n个字符" << endl;
36 string seven(four, 5, 2);
37 cout << "seven = " << seven << endl;
38
39 /*
40 cout << "8 --- string(string&& str) noexcept:将string对象初始化为str,并可能修改str,移动构造函数[C++11新特性]" << endl;
41
42 cout << "9 --- string(initializer_list<char>il:将string对象初始化为初始化列表il中的字符[C++11新特性]" << endl;
43 string nine = {'t', 'u', 'z', 'i'}; // or string nine{'t', 'u', 'z', 'i'};
44 cout << "nine = " << nine << endl;
45 */
46 }
View Code