const 常量函數只能調用其中的常量相關的東西。
struct StringLess:
public std::binary_function<const std::string&,
const std::string&,
bool>
{
bool operator()(const std::string& a, const std::string& b)const
{
return strcmp(a.c_str(),b.c_str());
}
};
std::map<std::string,Core::Rtti*,StringLess> nameTable;
Core::Rtti* Factory::GetRttiName(std::string className)const
{
return this->nameTable[className];
}
但是還發現出現錯誤。
g:\framework\foundation\foundation\core\factory.cpp(60) : error C2678: 二進制“[”: 沒有找到接受“const std::map<_Kty,_Ty,_Pr>”類型的左操作數的運算符(或沒有可接受的轉換)
with
[
_Kty=std::string,
_Ty=Core::Rtti *,
_Pr=StringLess
]
e:\microsoft visual studio 8\vc\include\map(166): 可能是“Core::Rtti *&std::map<_Kty,_Ty,_Pr>::operator [](const std::basic_string<_Elem,_Traits,_Ax> &)”
with
[
_Kty=std::string,
_Ty=Core::Rtti *,
_Pr=StringLess,
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
試圖匹配參數列表“(const std::map<_Kty,_Ty,_Pr>, std::string)”時
with
[
_Kty=std::string,
_Ty=Core::Rtti *,
_Pr=StringLess
]
這里主要是const函數的濫用,因為不清楚const函數究竟能對什么進行操作就濫用。
map的const對象不可以調[]。
operator[] 不是 const類型。
所以這個錯誤基本上將const去掉就好了。
這里總結一些東西,以前也濫用過const的東西
返回const表示這個返回內容是只讀的,不能被修改的。
參數使用const表示這個參數是只讀的,而不能進行任何修改,只參與計算,而不修改本身。
const常函數,只能對常量進行操作,說明在這里主要是進行常量成員的操作,而不做任何與const無關的操作,上面就是個很好的例子。