1、默认初始化
string s; //s是一个空串
2、使用字符串字面值初始化
string s1=“hello world”; //拷贝初始化
string s2(“hello world”); //直接初始化
注意:s1、s2的内容不包括’\0’
3、使用其他字符串初始化
string s2=s1; //拷贝初始化,s1是string类对象
string s2(s1); //直接初始化,s1是string类对象
4、使用单个字符初始化
string s(3 ‘a’); //直接初始化,s的内容是aaa
#include<iostream>
#include<string>
using namespace std;
int main(){
string s1;
string s2="hello world!";
string s3("hello world!");
string s4=s2;
string s5(s2);
string s6(3,'a');
cout<<"s1: "<<s1<<endl;
cout<<"s2: "<<s2<<endl;
cout<<"s3: "<<s3<<endl;
cout<<"s4: "<<s4<<endl;
cout<<"s5: "<<s5<<endl;
cout<<"s6: "<<s6<<endl;
return 0;
}
运行后为:
s1:
s2: hello world!
s3: hello world!
s4: hello world!
s5: hello world!
s6: aaa