18.1.1 string构造函数
官方给出了许多构造函数,但似乎不太容易看得懂:
basic_string();
explicit basic_string(
const allocator_type& alloc_type);
basic_string(
const basic_string& right);
basic_string(
basic_string&& right);
basic_string(
const basic_string& right,
size_type right_offset,
size_type count = npos);
basic_string(
const basic_string& right,
size_type right_offset,
size_type count,
const allocator_type& alloc_type);
basic_string(
const value_type* ptr,
size_type count);
basic_string(
const value_type* ptr,
size_type count,
const allocator_type& alloc_type);
basic_string(
const value_type* ptr);
basic_string(
const value_type* ptr,
const allocator_type& alloc_type);
basic_string(
size_type count,
value_type char_value);
basic_string(
size_type count,
value_type char_value,
const allocator_type& alloc_type);
template <class InputIterator>
basic_string(
InputIterator first,
InputIterator last);
template <class InputIterator>
basic_string(
InputIterator first,
InputIterator last,
const allocator_type& alloc_type);
basic_string(
const_pointer first,
const_pointer last);
basic_string(
const_iterator first,
const_iterator last);
- 第一个
basic_string();
是默认构造函数,只声明对象,不初始化。 - 第二个
explicit basic_string(const allocator_type& alloc_type);
是一个有参构造函数初始化string对象,参数类型为allocator_type。这个类型在string类的定义中提到过。 - ······
总结一下,常用的构造函数其实只有这几种:
string();
创建一个空字符串string(const char* s);
使用字符串s初始化string(const string& str);
使用一个string对象初始化另一个string对象string(int n, char c);
使用n个字符c初始化
示例:
#include <iostream>
#include <string>
using namespace std;
void test1()
{
//创建一个空字符串
string s1;
//使用字符串s初始化
const char* str = "hello world";
string s2(str);
cout << "s2=" << s2 << endl;
//使用一个string对象初始化另一个string对象
string s3(s2);
cout << "s3=" << s3 << endl;
//使用n个字符c初始化
string s4(10,'a');
cout << "s4=" << s4 << endl;
}
int main()
{
test1();
}