简单介绍四种string构造函数:
1、string() 创建一个空的字符串
2、string(const char* s) 使用字符串s初始化
3、string(const string& str) 使用一个string对象初始化另一个string对象
4、string(int n, char c) 使用n个字符c初始化
一、string() 创建一个空的字符串
略
二、string(const char* s) 使用字符串s初始化
#include<iostream>
using namespace std;
#include<string>
int main()
{
const char *temp = "hello world";
string str(temp);
cout << str << endl;
system("pause");
}
运行结果:
hello world
请按任意键继续. . .
三、string(const string& str) 使用一个string对象初始化另一个string对象
#include<iostream>
using namespace std;
#include<string>
int main()
{
string temp = "hello world";
string str(temp);
cout << str << endl;
system("pause");
}
运行结果:
hello world
请按任意键继续. . .
四、string(int n, char c) 使用n个字符c初始化
#include<iostream>
using namespace std;
#include<string>
int main()
{
string str(5, 'a');
cout << str << endl;
system("pause");
}
运行结果:
aaaaa
请按任意键继续. . .