https://blog.csdn.net/potxxx/article/details/87290812\
寫程序遇到一個Bug如下:
char x = 'a';
string str(x); //這裏報錯了
當時就有點蒙了,查了下string的構造函數:
string();
string (const string& str);
string (const string& str, size_t pos, size_t len = npos);
string (const char* s);
string (const char* s, size_t n);
string (size_t n, char c);
template <class InputIterator>
string (InputIterator first, InputIterator last);
string (initializer_list<char> il);
string (string&& str) noexcept;
果然沒有char類型直接初始化的(不知道爲啥不提供。。。)
於是想要將一個char轉換爲string只能找其他間接的方法了,這裏提供幾種:
//1、構造函數裏有個string(size_t,char)
char x = 'a';
string s(1,x);
//2、string初始化沒char,但是push_back可以
string s;
s.push_back(x);
//3、string可以由char*初始化
char xx[2] = {x,0};
string s(xx)
但是我還是要說這麼寫毫無美感,就讓人很難受。。。。
---------------------
作者:potxxx
來源:CSDN
原文:https://blog.csdn.net/potxxx/article/details/87290812
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!