4 更好的使用標(biāo)準(zhǔn)庫(kù)中的字符串類 (std::basic_string<class Char, class CharTraits, class Alloc>)

???如果在一個(gè)實(shí)際的項(xiàng)目中要使用標(biāo)準(zhǔn)庫(kù)的std::string 或 std::wstring,會(huì)發(fā)現(xiàn)隨著時(shí)間的推移,越會(huì)產(chǎn)生出重寫(xiě)一個(gè)自己的字符串類之沖動(dòng),而std::string的接口如此之好用,同時(shí)code里到處是std::string這樣的東西,有時(shí)又要向多字節(jié)字符轉(zhuǎn)換。此處有一個(gè)比較好的方案,不過(guò)最好從項(xiàng)目開(kāi)始就實(shí)施:
???typedef unsigned char UChar;
???typedef unsigned short UWChar;

???typedef std::allocator StringAllocator;???// 使得以后有針對(duì)字符串分配優(yōu)化

???typedef std::basic_string< UChar, std::char_traits<UChar>, StringAllocator<UChar> > String;
???typedef std::basic_string< UWChar, std::char_traits<UWChar>, StringAllocator<UWChar> > WString; // 寬字符版本

然后,在項(xiàng)目中就可以使用這個(gè)經(jīng)過(guò)定制的String / WString。

5 函數(shù)名稱重載是C++很好的特性,適當(dāng)使用會(huì)帶來(lái)很好的效果,有時(shí)卻會(huì)自找麻煩,下面就是一例:
???class EntityDefination {
???public:
??????//...
??????Entity* GetEntity(const char* name);
??????Entity* GetEntity(const unsigned?id);???// 重載
???};
???自認(rèn)為這樣很好不是嗎?
???有一次,我寫(xiě)了這樣一行代碼:
???Entity* result = entDef->GetEntity(0);
???知道,發(fā)生什么事嗎,這是個(gè)對(duì)GetEntity(const unsigned?id)的調(diào)用,雖說(shuō)這是一行測(cè)試代碼,但足以說(shuō)明我的類接口上的信息缺了些,遂做了如下改動(dòng):
??????Entity* GetEntityByName(const char* name);
??????Entity* GetEntityByID(const unsigned id);

然后,看看:
?????Entity× result = entDef->GetEntityById(0);???// 哈哈!錯(cuò)誤一目了然,眼睛調(diào)試 :)



(to be continued!)