代码
#include <iostream>
#include <string>
//string构造函数
int main() {
using namespace std;
//NBTS 表示以空字符串结束的字符串
//ctor 表示构造函数
//构造函数:str(const char*s) 将string对象初始化为s指向的NBTS
string one("Lottery Winner!"); // ctor #1
cout << one << endl; // overloaded <<
//----------------------------------------------------------
//构造函数:str(size_type n ,char c) 创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
string two(20, '$'); // ctor #2
cout << two << endl;
//----------------------------------------------------------
//string(const string&str) 复制构造函数
string three(one); // ctor #3
cout << three << endl;
//----------------------------------------------------------
one += " Oops!"; // overloaded +=
cout << one << endl;
two = "Sorry! That was ";
three[0] = 'P';
string four; // ctor #4
four = two + three; // overloaded +, =
cout << four << endl;
//----------------------------------------------------------
//将string对象的初始化为s指向的NBTS的前n个字符,即使超过了NBTS结尾
//string(const string& str ,string size_type)
char alls[] = "All's well that ends well";
string five(alls, 20); // ctor #5
cout << five << "!\n";
//----------------------------------------------------------
//template<class Iter>
//string (Iter begin,Iter end) //模板参数Iter
string six(alls + 6, alls + 10); // ctor #6
cout << six << ", "; //alls 数组相当于指针,所以alls+6 类型是char*
//----------------------------------------------------------
//string seven(five+6 , five+10) 不能,对象名(string) 不同于数组名,不会被看作是对象的地址,因此five不是指针。
//five[6] 是一个char值,所以&five[6] 是一个地址。
string seven(&five[6], &five[10]); // ctor #6 again
cout << seven << "...\n";
//----------------------------------------------------------
string eight(four, 7, 16); // ctor #7
//将一个string对象的部分内容复制到构造的对象中
//从four的第8个字符(位置7)开始,将16个字符复制到eight中
cout << eight << " in motion!" << endl;
return 0;
}
//----------------------------------------------------------
//Lottery Winner!
//$$$$$$$$$$$$$$$$$$$$
//Lottery Winner!
//Lottery Winner!Oops!
//Sorry!That was Pottery Winner!
//All's well that ends!
//well, well...
//That was Pottery in motion!
c++11新增的构造函数
string(string && str)
类似于复制函数,导致新创建的string为str的副本。但与复制构造函数不同的是,它不能保证将str视为const,称为移动构造函数- 编译器使用这个以优化性能。
stirng(initialize_list<char> il)
string pi = {'l','i','s'}
string pi { 'l' , 'i', 's'}
- 这可能用处不大,因为使用char* 更容易