【C++】初始化string对象的几种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wingrez/article/details/87905253

初始化string对象的几种方式

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(10, ‘a’); //直接初始化,s的内容是aaaaaaaaaa

示例

#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(10,'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;
}/*output
s1:
s2: hello world!
s3: hello world!
s4: hello world!
s5: hello world!
s6: aaaaaaaaaa

*/

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/87905253
今日推荐