C++ 中const對象與const成員函數(shù)的實例詳解
C++ 中const對象與const成員函數(shù)的實例詳解
const對象只能調(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個fun注釋掉就會出錯:error C2662: “A::fun”: 不能將“this”指針從“const A”轉(zhuǎn)換為“A &”。
但是const成員函數(shù)可以被非const 對象調(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ù)!
當然非const對象可以調(diào)用非const成員函數(shù)。
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
OpenCV實現(xiàn)簡單攝像頭視頻監(jiān)控程序
這篇文章主要為大家詳細介紹了OpenCV實現(xiàn)簡單攝像頭視頻監(jiān)控程序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08在C++中把字符串轉(zhuǎn)換為整數(shù)的兩種簡單方法
經(jīng)常會遇到類型轉(zhuǎn)換,本文主要介紹了C++中把字符串轉(zhuǎn)換為整數(shù)的兩種簡單方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06