字符串/数字自动转换的ID类【分享】

最近在研究游戏编程,游戏里面很多ID有时候要当字符串用,有时候要当数字用,不胜其烦。就想搞个自动转换字符串和ID的类,来避免这种麻烦,于是找到了网上某人的一段代码,分享一下。

#include

#include

template
class AutoId {
public:
AutoId() {
mNum = T(0);
mStr = “”;
mNumDirty = false;
mStrDirty = true;
}
AutoId(T n) {
mNum = n;
mNumDirty = false;
mStrDirty = true;
}
AutoId(const std::string &s) {
mStr = s;
mStrDirty = false;
mNumDirty = true;
}
AutoId(const AutoId &other) {
mNum = other.mNum;
mStr = other.mStr;
mNumDirty = other.mNumDirty;
mStrDirty = other.mStrDirty;
}
~AutoId() {
}
AutoId &operator = (const AutoId &other) {
mNum = other.mNum;
mStr = other.mStr;
mNumDirty = other.mNumDirty;
mStrDirty = other.mStrDirty;
return this;
}
AutoId &operator = (T n) {

// 用数字赋值
mNum = n;
mNumDirty = false;
mStrDirty = true;
return *this;
}
AutoId &operator = (const std::string &s) {

// 用字符串赋值
mStr = s;
mStrDirty = false;
mNumDirty = true;
return *this;
}
operator T(void) {

// 赋值给数字
if(mNumDirty) {
assert(!mStrDirty);
std::istringstream ss(mStr);
ss >> mNum;
mNumDirty = false;
}
return mNum;
}
operator std::string(void) {

// 赋值给字符串
if(mStrDirty) {
assert(!mNumDirty);
std::ostringstream ss;
ss << mNum;
mStr = ss.str();
mStrDirty = false;
}
return mStr;
}
private:
T mNum;
std::string mStr;
bool mNumDirty;
bool mStrDirty;
};

想要实现自动转换字符串和数字功能,示例代码如下:

AutoId id1(5);
AutoId id2(“3.14”);
AutoId id3; id3 = 400;
AutoId id4; id4 = “5423.234236”;

int nid1 = id1;
std::string sid1 = id1;

float nid2 = id2;
std::string sid2 = id2;

unsigned int nid3 = id3;
std::string sid3 = id3;

double nid4 = id4;
std::string sid4 = id4;

// 但是不能直接当作字符串用,比如
id4.c_str(); // 错误代码

代码就是这么些了,希望这个能自动转换数字和字符串的类能给大家编程带来帮助。