c++之const成員函數強制調用非const成員函數


我們都知道const成員函數只能調用非const成員函數

但是有的時候,我們為了代碼復用
例如:
    T operator[](int i) const;
    T& operator[](int i);

為了實現const和非const兩個版本,我們選擇使用重載,但是里面的內容可能是相同的,為了代碼復用可以:

    T& operator[](int i) {
        if( (i >= 0) && (i < m_length) ) {
            return m_array[i];
        }
        else {
            THROW_EXCEPTION(IndexOutOfBoundsException, "T& operator[](int i) i");
        }
    }
    T operator[](int i) const{
        return const_cast<SeqList&>(*this)[i];
    }

使用 const_cast<SeqList&>(this),把const版本的this轉化為非const然后調用非const版本的[],因為const只在編譯期,在運行期是不存在const的


免責聲明!

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



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