名稱空間
變體
操作

std::basic_string<CharT,Traits,Allocator>::operator+=

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
basic_string& operator+=( const basic_string& str );
(1) (C++20 起為 constexpr)
basic_string& operator+=( CharT ch );
(2) (C++20 起為 constexpr)
basic_string& operator+=( const CharT* s );
(3) (C++20 起為 constexpr)
basic_string& operator+=( std::initializer_list<CharT> ilist );
(4) (C++11 起)
(C++20 起為 constexpr)
template< class StringViewLike >
basic_string& operator+=( const StringViewLike& t );
(5) (C++17 起)
(C++20 起為 constexpr)

將附加字元新增到字串。

1) 附加字串 str
2) 附加字元 ch
3) 附加 s 所指向的空終止字元字串。
4) 附加初始化列表 ilist 中的字元。
5) 隱式將 t 轉換為字串檢視 sv,如同透過 std::basic_string_view<CharT, Traits> sv = t;,然後附加字串檢視 sv 中的字元,如同透過 append(sv)
此過載僅當 std::is_convertible_v<const StringViewLike&,
                      std::basic_string_view<CharT, Traits>>
truestd::is_convertible_v<const StringViewLike&, const CharT*>false 時才參與過載決議。

目錄

[編輯] 引數

str - 要附加的字串
ch - 要附加的字元值
s - 指向要附加的空終止字元字串的指標
ilist - 包含要附加字元的 std::initializer_list
t - 包含要附加字元的物件(可轉換為 std::basic_string_view

[編輯] 返回值

*this

[編輯] 複雜度

沒有標準複雜度保證,典型實現的行為類似於 std::vector::insert()

[編輯] 異常

如果操作導致 size() 超過 max_size(),則丟擲 std::length_error

如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。

[編輯] 注意

過載 (2) 可以接受任何隱式可轉換為 CharT 的型別。對於 std::string,其中 CharTchar,可接受的型別集包括所有算術型別。這可能會產生意外的效果。

[編輯] 示例

#include <iomanip>
#include <iostream>
#include <string>
 
int main()
{
    std::string str;
 
    // reserve sufficient storage space to avoid memory reallocation
    str.reserve(50);
 
    std::cout << std::quoted(str) << '\n'; // empty string
 
    str += "This";
    std::cout << std::quoted(str) << '\n';
 
    str += std::string(" is ");
    std::cout << std::quoted(str) << '\n';
 
    str += 'a';
    std::cout << std::quoted(str) << '\n';
 
    str += {' ', 's', 't', 'r', 'i', 'n', 'g', '.'};
    std::cout << std::quoted(str) << '\n';
 
    str += 69.96; // Equivalent to str += static_cast<char>(69.96);
                  // 'E' (ASCII code 69) is appended by overload (2),
                  // which might not be the intent.
 
    // To add a numeric value, consider std::to_string():
    str += std::to_string(1729);
 
    std::cout << std::quoted(str) << '\n';
}

輸出

""
"This"
"This is "
"This is a"
"This is a string."
"This is a string.E1729"

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 847 C++98 沒有異常安全保證 添加了強異常安全保證
LWG 2946 C++17 過載 (5) 在某些情況下導致歧義 透過使其成為模板來避免

[編輯] 參閱

將字元追加到末尾
(public member function) [編輯]