發現一個奇怪的問題,mark
class Demo
{
public:
std::vector<int> *getVector()const;
const std::vector<int> *getVector()const;
std::vector<int> *getExternVector()const;
private:
std::vector<int> m_vecInt;
};
std::vector<int> *Demo::getVector()const //
{
return &m_vecInt; //編譯出錯,無法從"const std::vector<int>* "轉換為"std::vector<int>*"
}
const std::vector<int> *Demo::getVector()const
{
return &m_vecInt; //編譯ok
}
std::vector<int> *Demo::getExternVector()const
{
auto pVec = new std::vector<int>;//編譯ok。(當然不提倡)
return pVec;
}
總結:1、const成員函數對成員變量有“保護趨向”,
std::vector<int>* getVector() const
{
return &m_vecInt;
//相當於
const std::vector<int> *pRetVal = &m_vecInt;
return pRetVal;
}
2、而對於非成員變量,則不這樣做。
