C++類的常成員函數以及靜態成員函數__Jquery

來源:互聯網
上載者:User

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;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.