string构造函数
时间: 2023-11-18 14:04:39 浏览: 33
string构造函数是用于创建string对象的函数,它可以接受不同类型的参数,包括字符指针、字符数组、另一个string对象等。常见的string构造函数有以下几种:
1. 默认构造函数:创建一个空的string对象。
2. 字符串字面值构造函数:接受一个字符串字面值作为参数,创建一个包含该字符串的string对象。
3. 字符指针构造函数:接受一个字符指针作为参数,创建一个包含该指针指向的字符串的string对象。
4. 复制构造函数:接受一个已有的string对象作为参数,创建一个与之相同的新对象。
例如,以下代码演示了使用不同类型参数调用string构造函数创建对象的方法:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
// 默认构造函数
string s1;
// 字符串字面值构造函数
string s2("hello");
// 字符指针构造函数
char str[] = "world";
string s3(str);
// 复制构造函数
string s4(s2);
cout << s1 << endl; // 输出空字符串
cout << s2 << endl; // 输出 hello
cout << s3 << endl; // 输出 world
cout << s4 << endl; // 输出 hello
return 0;
}
```