您好,登录后才能下订单哦!
密码登录
            
            
            
            
        登录注册
            
            
            
        点击 登录注册 即表示同意《亿速云用户服务条款》
        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() );
运行之后,
乜有错误,那么来看一下它的运行结果。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。