C++中const修饰的成员函数

2023-06-26,,

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;
}

运行之后:

我们发现,程序并没有报错,也就是说,用const修饰对象是完全可以的。那么,比如,我们现在想要使用这个const修饰的对象。比如:

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

运行一下程序,我们可以发现:

程序报错了。
由此可知,我们用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修饰的成员函数.doc》

下载本文的Word格式文档,以方便收藏与打印。