// 通用库
// String.h
namespace Common
{
class CString : public string
{
public:
CString();
virtual ~CString();
// 模版化构造函数
template <typename T>
CString(const T& tVal)
{
ostringstream oss;
oss << tVal;
assign(oss.str());
}
// 模版化类型转换(注意char*不可用)
template <typename T>
operator T()
{
T tVal;
istringstream iss(this->c_str());
iss >> tVal;
return tVal;
}
// 重载+运算符
template <typename T>
CString operator +(const T& tVal)
{
return CString((this->c_str() + CString(tVal)));
}
// 重载=运算符
template <typename T>
CString& operator =(const T& tVal)
{
this->assign(CString(tVal));
return *this;
}
// 重载+=运算符
template <typename T>
CString& operator +=(const T& tVal)
{
this->append(CString(tVal));
return *this;
}
// 重载<<运算符
template <typename T>
CString& operator <<(const T& tVal)
{
this->append(CString(tVal));
return *this;
}
// 重载<<运算符
template <typename T>
CString& operator >>(T& tVal)
{
istringstream iss(this->c_str());
iss >> tVal;
return *this;
}
// 格式化字符串
CString& Format(const char* pFormat, ...);
// 转换为大写
CString& Toupper();
// 转换为小写
CString& Tolower();
};
// 转换为char*类型
template<> CString::operator char*();
// 转换为const char*类型
template<> CString::operator const char*();
}
// String.cpp
namespace Common
{
CString::CString()
{
//ctor
}
CString::~CString()
{
//dtor
}
// 转换为char*类型
template <>
CString::operator char*()
{
return (char*)this->c_str();
}
// 转换为const char*类型
template <>
CString::operator const char*()
{
return this->c_str();
}
// 格式化字符串
CString& CString::Format(const char* pFormat, ...)
{
char* pBuff = NULL;
va_list params;
pBuff = new char[MAX_FORMAT_SIZE];
memset(pBuff, 0, MAX_FORMAT_SIZE);
va_start(params, pFormat);
vsnprintf(pBuff, MAX_FORMAT_SIZE, pFormat, params);
va_end(params);
this->assign(pBuff);
delete[] pBuff;
return *this;
}
// 转换为大写
CString& CString::Toupper()
{
transform(this->begin(), this->end(), this->begin(), ::toupper);
return *this;
}
// 转换为小写
CString& CString::Tolower()
{
transform(this->begin(), this->end(), this->begin(), ::tolower);
return *this;
}
}
增强CString类(字符数值自由转换)
最新推荐文章于 2022-06-09 00:39:13 发布