c++ const成員函數返回值問題。


發現一個奇怪的問題,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、而對於非成員變量,則不這樣做。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM