18.1.1 string构造函数

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();
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值