C++ 中const對(duì)象與const成員函數(shù)的實(shí)例詳解
C++ 中const對(duì)象與const成員函數(shù)的實(shí)例詳解
const對(duì)象只能調(diào)用const成員函數(shù):
#include<iostream>
using namespace std;
class A
{
public:
void fun()const
{
cout<<"const 成員函數(shù)!"<<endl;
}
void fun()
{
cout<<"非const成員函數(shù) !"<<endl;
}
};
int main()
{
const A a;
a.fun();
}
輸出:const 成員函數(shù)!
但是如果把第以1個(gè)fun注釋掉就會(huì)出錯(cuò):error C2662: “A::fun”: 不能將“this”指針從“const A”轉(zhuǎn)換為“A &”。
但是const成員函數(shù)可以被非const 對(duì)象調(diào)用:
#include<iostream>
using namespace std;
class A
{
public:
void fun()const
{
cout<<"const 成員函數(shù)!"<<endl;
}
/* void fun()
{
cout<<"非const成員函數(shù) !"<<endl;
}
*/
};
int main()
{
A a;
a.fun();
}
該段代碼輸出:const 成員函數(shù)!
當(dāng)然非const對(duì)象可以調(diào)用非const成員函數(shù)。
如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
北郵計(jì)算機(jī)考研復(fù)試題的C語(yǔ)言解答精選
這篇文章主要介紹了北郵計(jì)算機(jī)考研復(fù)試題目的C語(yǔ)言解答精選,選自2012年的一些基礎(chǔ)的上機(jī)題目,需要的朋友可以參考下2015-08-08
C++實(shí)現(xiàn)LeetCode(190.顛倒二進(jìn)制位)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(190.顛倒二進(jìn)制位),本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
深入c語(yǔ)言continue和break的區(qū)別詳解
本篇文章是對(duì)c語(yǔ)言中continue和break的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

