C++ 類的靜態(tài)成員

C++ 類 & 對象 C++ 類 & 對象

我們可以使用 static 關(guān)鍵字來把類成員定義為靜態(tài)的。當(dāng)我們聲明類的成員為靜態(tài)時,這意味著無論創(chuàng)建多少個類的對象,靜態(tài)成員都只有一個副本。

靜態(tài)成員在類的所有對象中是共享的。如果不存在其他的初始化語句,在創(chuàng)建第一個對象時,所有的靜態(tài)數(shù)據(jù)都會被初始化為零。我們不能把靜態(tài)成員放置在類的定義中,但是可以在類的外部通過使用范圍解析運算符 :: 來重新聲明靜態(tài)變量從而對它進行初始化,如下面的實例所示。

下面的實例有助于更好地理解靜態(tài)數(shù)據(jù)成員的概念:

#include <iostream>
 
using namespace std;

class Box
{
   public:
      static int objectCount;
      // 構(gòu)造函數(shù)定義
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // 每次創(chuàng)建對象時增加 1
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // 長度
      double breadth;    // 寬度
      double height;     // 高度
};

// 初始化類 Box 的靜態(tài)成員
int Box::objectCount = 0;

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // 聲明 box1
   Box Box2(8.5, 6.0, 2.0);    // 聲明 box2

   // 輸出對象的總數(shù)
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

Constructor called.
Constructor called.
Total objects: 2

靜態(tài)函數(shù)成員

如果把函數(shù)成員聲明為靜態(tài)的,就可以把函數(shù)與類的任何特定對象獨立開來。靜態(tài)成員函數(shù)即使在類對象不存在的情況下也能被調(diào)用,靜態(tài)函數(shù)只要使用類名加范圍解析運算符 :: 就可以訪問。

靜態(tài)成員函數(shù)只能訪問靜態(tài)數(shù)據(jù)成員,不能訪問其他靜態(tài)成員函數(shù)和類外部的其他函數(shù)。

靜態(tài)成員函數(shù)有一個類范圍,他們不能訪問類的 this 指針。您可以使用靜態(tài)成員函數(shù)來判斷類的某些對象是否已被創(chuàng)建。

下面的實例有助于更好地理解靜態(tài)函數(shù)成員的概念:

#include <iostream>
 
using namespace std;

class Box
{
   public:
      static int objectCount;
      // 構(gòu)造函數(shù)定義
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // 每次創(chuàng)建對象時增加 1
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // 長度
      double breadth;    // 寬度
      double height;     // 高度
};

// 初始化類 Box 的靜態(tài)成員
int Box::objectCount = 0;

int main(void)
{
  
   // 在創(chuàng)建對象之前輸出對象的總數(shù)
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // 聲明 box1
   Box Box2(8.5, 6.0, 2.0);    // 聲明 box2

   // 在創(chuàng)建對象之后輸出對象的總數(shù)
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

C++ 類 & 對象 C++ 類 & 對象