const 常量函數(shù)只能調(diào)用其中的常量相關(guān)的東西。
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];
}
但是還發(fā)現(xiàn)出現(xiàn)錯(cuò)誤。
g:\framework\foundation\foundation\core\factory.cpp(60) : error C2678: 二進(jìn)制“[”: 沒(méi)有找到接受“const std::map<_Kty,_Ty,_Pr>”類型的左操作數(shù)的運(yùn)算符(或沒(méi)有可接受的轉(zhuǎn)換)
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>
]
試圖匹配參數(shù)列表“(const std::map<_Kty,_Ty,_Pr>, std::string)”時(shí)
with
[
_Kty=std::string,
_Ty=Core::Rtti *,
_Pr=StringLess
]
這里主要是const函數(shù)的濫用,因?yàn)椴磺宄onst函數(shù)究竟能對(duì)什么進(jìn)行操作就濫用。
map的const對(duì)象不可以調(diào)[]。
operator[] 不是 const類型。
所以這個(gè)錯(cuò)誤基本上將const去掉就好了。
這里總結(jié)一些東西,以前也濫用過(guò)const的東西
返回const表示這個(gè)返回內(nèi)容是只讀的,不能被修改的。
參數(shù)使用const表示這個(gè)參數(shù)是只讀的,而不能進(jìn)行任何修改,只參與計(jì)算,而不修改本身。
const常函數(shù),只能對(duì)常量進(jìn)行操作,說(shuō)明在這里主要是進(jìn)行常量成員的操作,而不做任何與const無(wú)關(guān)的操作,上面就是個(gè)很好的例子。