c++ 中的const 成員函數

源地址:http://bbs.csdn.net/topics/300206022

const 成員函數:QVariant Cell::evalExpression(const QString &str, int &pos) const;
==> augment : QVariant Cell::evalExpression(const QString &str, int &pos, const Cell * const this);
正常成員函數:QVariant Cell::evalExpression(const QString &str, int &pos) ;
==> augment : QVariant Cell::evalExpression(const QString &str, int &pos, Cell * const this);


Cell *const this: 意味着this是一個常量指針,始終指向這個對象(但這個對象可以改變,只是this指針不能改爲指向其他對象);
const Cell *const this: 除了含有上面的意思外,還說明了,this這個指針所指向的對象也是不可變的。

//c++ primer(中文第五版)中p56。
即成員函數後面加上const限定符後,表達了這個成員函數不會改變當前對象中的數據。



用途例子:重載輸出運算符
class String // 僅僅是一個類的例子
{
            public:
            char display() const; // 此const 成員函數用於輸出一個字符
             .....
            private:
            ......
            friend ostream & operator<<(ostream &os, const String &str); // 定義了一個友元函數以使重載後的輸出運算符可以訪問String中的內容
};
ostream &operator<<(ostream &os, const String &str)
{
           os << str.display();//於此調用了display 函數,且實參str中含有const,爲了讓編譯器可以確定str引用的對象不會被修改
                                           //所以必須讓display函數不能修改當前對象,故display函數必須爲const 成員函數,否則報錯。
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章