1. 程式人生 > >[C++] 類中的靜態成員

[C++] 類中的靜態成員

部分 pre www. 相關 定義 output stat 數據 ini

代碼部分轉載自:C++ 類的靜態成員及靜態成員函數

1、類的靜態成員與類本身相關,與類的各個對象無關,它存在於任何對象之外,所有的對象共享靜態成員,所以在計算對象大小時,不包含靜態數據成員。 2、靜態成員函數不能聲明為const的,因為這樣非const對象就不能使用了;並且不包含this指針,因為this指針是針對具體對象的,這樣靜態成員函數就不能調用非靜態成員。 3、靜態數據成員不屬於類的任何一個對象,不是由類的構造函數初始化的,必須在類的外部定義和初始化每個靜態成員。 4、靜態數據成員一旦被定義,就將一直存在於程序的整個生命周期中。 5、下面通過幾個例子來總結靜態成員變量和靜態成員函數的使用規則。

  一、通過類名調用靜態成員函數和非靜態成員函數

//例子一:通過類名調用靜態成員函數和非靜態成員函數
class Point{
public:
    void init()
    {}

    static void output()
    {}
};

void main()
{
    Point::init();
    Point::output();
}

編譯出錯:錯誤 1 error C2352: “Point::init”: 非靜態成員函數的非法調用

結論一:不能通過類名來調用類的非靜態成員函數

二、通過類的對象調用靜態成員函數和非靜態成員函數

//例子二:通過類的對象調用靜態成員函數和非靜態成員函數
class
Point{ public: void init() { } static void output() {} }; void main() { Point pt; pt.init(); pt.output(); }

 編譯通過。

 結論二:類的對象可以使用靜態成員函數和非靜態成員函數。

三、在類的靜態成員函數中使用類的非靜態成員

//例子三:在類的靜態成員函數中使用類的非靜態成員
#include <iostream>
using namespace std;

class Point{
public:
    
void init() { } static void output() { cout << "m_x=" << m_x << endl; } private: int m_x; }; void main() { Point pt; pt.output(); }

 編譯出錯:IntelliSense: 非靜態成員引用必須與特定對象相對

  因為靜態成員函數屬於整個類,在類實例化對象之前就已經分配空間了,而類的非靜態成員必須在類實例化對象後才有內存空間,所以這個調用就會出錯,就好比沒有聲明一個變量卻提前使用它一樣。

  結論三:靜態成員函數中不能引用非靜態成員。

四、在類的非靜態成員函數中使用類的靜態成員

//例子四:在類的非靜態成員函數中使用類的靜態成員
#include <iostream>
using namespace std;

class Point{
public:
    void init()
    {
        output();
    }
    static void output()
    {
    }
private:
    int m_x;
};
void main()
{
    Point pt;
    pt.init();
}

編譯通過。

結論四:類的非靜態成員可以調用靜態成員函數,但反之不能。

五、使用類的靜態成員變量

//例子五:使用類的靜態成員變量
#include <iostream>
using namespace std;

class Point{
public:
    Point()
    {
        m_nPointCount++;
    }
    ~Point()
    {
        m_nPointCount++;
    }
    static void output()
    {
        cout << "m_nPointCount=" << m_nPointCount << endl;
    }
private:
    static  int m_nPointCount;
};

void main()
{
    Point pt;
    pt.output();
}

鏈接出錯:error LNK2001: 無法解析的外部符號 "private: static int Point::m_nPointCount" (?m_nPointCount@Point@@0HA)

這是因為類的成員變量在使用前必須先初始化。

改成如下代碼即可:

#include <iostream>
using namespace std;

class Point{
public:
    Point()
    {
        m_nPointCount++;
    }
    ~Point()
    {
        m_nPointCount++;
    }
    static void output()
    {
        cout << "m_nPointCount=" << m_nPointCount << endl;
    }
private:
    static  int m_nPointCount;
};

//類外初始化靜態成員變量時,不用帶static關鍵字
int Point::m_nPointCount = 0;
void main()
{
    Point pt;
    pt.output();
}

結論五:類的靜態成員變量必須先初始化再使用。

[C++] 類中的靜態成員