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修饰的对象。好比:ide
printf ( "the foot :%d\n", hashiqi.getFoot() );
运行一下程序,咱们能够发现:
程序报错了。
由此可知,咱们用const修饰的对象,不能直接调用成员函数。那么,该怎么办呢?答案是调用const成员函数。
先来看一下const成员函数的格式:函数
Type ClassName:: function ( Type p ) const
也就是说,只要在函数后加上一个const就能够了。那么,咱们来编程实验一下,是否能够this
int getFoot ( void ) const{ return this->foot; } int getEar ( void ) const{ return this->ear; }
const Dog hashiqi; printf ( "the foot :%d\n", hashiqi.getFoot() );
运行以后,
乜有错误,那么来看一下它的运行结果。code