C++中const修飾的成員函數

As we all konw,const能夠用來修飾變量,那麼const是否能用來修飾對象呢?關於這一點,我們可以做一個小實驗,實驗一下:

#include <stdio.h>
#include <stdlib.h>

class Dog{

private:
    int foot;
    int ear;
public:
    Dog (){

        this->foot = 4;
        this->ear = 2;
    }
    int getFoot ( void ){

        return this->foot;
    }
    int getEar ( void ){

        return this->ear;
    }
    void setFoot ( int foot ){

        this->foot = foot;
    }
    void setEar ( int ear ){

        this->ear = ear;
    }
};

int main ( int argc, char** argv ){

    const Dog hashiqi;

    system ( "pause" );
    return 0;
}

運行之後:
C++中const修飾的成員函數
我們發現,程序並沒有報錯,也就是說,用const修飾對象是完全可以的。那麼,比如,我們現在想要使用這個const修飾的對象。比如:

printf ( "the foot :%d\n", hashiqi.getFoot() );

運行一下程序,我們可以發現:
C++中const修飾的成員函數
程序報錯了。
由此可知,我們用const修飾的對象,不能直接調用成員函數。那麼,該怎麼辦呢?答案是調用const成員函數。
先來看一下const成員函數的格式:

Type ClassName:: function ( Type p ) const

也就是說,只要在函數後加上一個const就可以了。那麼,我們來編程實驗一下,是否可以

int getFoot ( void ) const{

        return this->foot;
    }
    int getEar ( void ) const{

        return this->ear;
    }
const Dog hashiqi;

    printf ( "the foot :%d\n", hashiqi.getFoot() );

運行之後,
C++中const修飾的成員函數
乜有錯誤,那麼來看一下它的運行結果。
C++中const修飾的成員函數

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