天天看點

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 成員函數,否則報錯。

}

繼續閱讀