1 常成員函數
1.1聲明:<類型標識符>函數名(形參列表)const;
1.2說明:
1)const是函數類型的一部分,在實現部分也要帶上該關鍵字;
2)const關鍵字可以用於對重載函數的區分;
3)常成員函數不能更新類的成員變數,也不可以調用類中沒有用const修飾的成員函數,只能調用常成員函數,但是可以被其他成員函數調用;
4)特別地:常對象只能訪問類中const成員函數(除了系統自動調用的隱含建構函式以及解構函式)
1.3常式:
class A{private: int w, h;public: int getValue()const; int getValue(); A(int x, int y):w(x), h(y){} A(){} ~A(){}};int A::getValue()const{ return w*h;}int A::getValue(){ return w+h;}int main(){ const A a(1, 2); A c(1,2); cout << a.getValue() << endl;//調用const成員函數 cout << c.getValue() << endl;//調用非const成員函數 return 0;}
2 靜態成員函數
使用static修飾的成員函數,只能被定義一次,而且要被同類的所有對象所共用,它是類的一種行為,與對象無關,它有如下特點:
1)靜態函數成員不可以直接存取類中非待用資料成員以及非靜態成員函數,只能通過對象名(由參數傳入)來訪問;
2)靜態成員函數在類外實現時,無需加static修飾,否則出錯;
3)在類外,可以通過對象名以及類名來調用類的靜態成員函數。
class B{private: int x; int y; static int count;public: B():x(0), y(0){ count++; } B(int xx, int yy):x(xx), y(yy){ count++; } static int getObjCount();};int B::count = 0;int B::getObjCount(){ return count;}int main(){ cout << B::getObjCount() << endl; B b1; B b2(10, 20); cout << b1.getObjCount() << endl; cout << b2.getObjCount() << endl; cout << B::getObjCount() << endl; return 0;}