As we all konw,const能夠用來(lái)修飾變量,那么const是否能用來(lái)修飾對(duì)象呢?關(guān)于這一點(diǎn),我們可以做一個(gè)小實(shí)驗(yàn),實(shí)驗(yàn)一下:
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、重慶小程序開(kāi)發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了阿城免費(fèi)建站歡迎大家使用!
#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;
}
運(yùn)行之后:
我們發(fā)現(xiàn),程序并沒(méi)有報(bào)錯(cuò),也就是說(shuō),用const修飾對(duì)象是完全可以的。那么,比如,我們現(xiàn)在想要使用這個(gè)const修飾的對(duì)象。比如:
printf ( "the foot :%d\n", hashiqi.getFoot() );
運(yùn)行一下程序,我們可以發(fā)現(xiàn):
程序報(bào)錯(cuò)了。
由此可知,我們用const修飾的對(duì)象,不能直接調(diào)用成員函數(shù)。那么,該怎么辦呢?答案是調(diào)用const成員函數(shù)。
先來(lái)看一下const成員函數(shù)的格式:
Type ClassName:: function ( Type p ) const
也就是說(shuō),只要在函數(shù)后加上一個(gè)const就可以了。那么,我們來(lái)編程實(shí)驗(yàn)一下,是否可以
int getFoot ( void ) const{
return this->foot;
}
int getEar ( void ) const{
return this->ear;
}
const Dog hashiqi;
printf ( "the foot :%d\n", hashiqi.getFoot() );
運(yùn)行之后,
乜有錯(cuò)誤,那么來(lái)看一下它的運(yùn)行結(jié)果。
新聞名稱:C++中const修飾的成員函數(shù)
網(wǎng)站URL:http://bm7419.com/article48/goichp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、外貿(mào)建站、網(wǎng)站排名、用戶體驗(yàn)、定制開(kāi)發(fā)、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)