4 更好的使用標準庫中的字符串類 (std::basic_string<class Char, class CharTraits, class Alloc>)
???如果在一個實際的項目中要使用標準庫的std::string 或 std::wstring,會發現隨著時間的推移,越會產生出重寫一個自己的字符串類之沖動,而std::string的接口如此之好用,同時code里到處是std::string這樣的東西,有時又要向多字節字符轉換。此處有一個比較好的方案,不過最好從項目開始就實施:
???typedef unsigned char UChar;
???typedef unsigned short UWChar;
???typedef std::allocator StringAllocator;???// 使得以后有針對字符串分配優化
???typedef std::basic_string< UChar, std::char_traits<UChar>, StringAllocator<UChar> > String;
???typedef std::basic_string< UWChar, std::char_traits<UWChar>, StringAllocator<UWChar> > WString; // 寬字符版本
然后,在項目中就可以使用這個經過定制的String / WString。
5 函數名稱重載是C++很好的特性,適當使用會帶來很好的效果,有時卻會自找麻煩,下面就是一例:
???class EntityDefination {
???public:
??????//...
??????Entity* GetEntity(const char* name);
??????Entity* GetEntity(const unsigned?id);???// 重載
???};
???自認為這樣很好不是嗎?
???有一次,我寫了這樣一行代碼:
???Entity* result = entDef->GetEntity(0);
???知道,發生什么事嗎,這是個對GetEntity(const unsigned?id)的調用,雖說這是一行測試代碼,但足以說明我的類接口上的信息缺了些,遂做了如下改動:
??????Entity* GetEntityByName(const char* name);
??????Entity* GetEntityByID(const unsigned id);
然后,看看:
?????Entity× result = entDef->GetEntityById(0);???// 哈哈!錯誤一目了然,眼睛調試 :)
(to be continued!)