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

C++中const修饰对象
本文通过实例介绍了C++中如何使用const关键字修饰对象,并解释了如何调用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修饰的成员函数

转载于:https://blog.51cto.com/chen0547/2052589

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值