1. 程式人生 > >c++字串與任意型別資料拼接

c++字串與任意型別資料拼接

      C++的string類非常好用,不過跟VB比起來有些不足的就是VB支援任意型別資料拼接在一起,比如: 123 & “abc” & “56” & 111 (&為拼接操作符),為了解決這個問題,我們過載一下&運算子,讓C++的string類也支援這個操作。

#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;
}
輸出結果:4523651.55