c++字串與任意型別資料拼接
阿新 • • 發佈:2019-02-17
C++的string類非常好用,不過跟VB比起來有些不足的就是VB支援任意型別資料拼接在一起,比如: 123 & “abc” & “56” & 111 (&為拼接操作符),為了解決這個問題,我們過載一下&運算子,讓C++的string類也支援這個操作。
輸出結果:4523651.55#include <iostream> #include <string> #include <sstream> using namespace std; template <typename T> string operator &(const T &_t, const string &s) { ostringstream oss; oss << _t; return oss.str() + s; } template <typename T> string operator &(const string &s, const T &_t) { ostringstream oss; oss << _t; return s + oss.str() ; } int main(int argc, char *argv[]) { string ret; ret = string("45") + "23" & 65 & 1.55; cout << ret << endl; return 0; }