C++ |類的靜態(tài)成員變量和函數(shù)
發(fā)布時(shí)間:2023-12-13 14:14:16
類的成員函數(shù)是指那些把定義和原型寫在類定義內(nèi)部的函數(shù),就像類定義中的其他變量一樣。類成員函數(shù)是類的一個(gè)成員,它可以操作類的任意對象,可以訪問對象中的所有成員。C++是面向?qū)ο蟮木幊陶Z言,對象就是面向?qū)ο蟪绦蛟O(shè)計(jì)的核心。所謂對象就是真實(shí)世界中的實(shí)體,對象與實(shí)體是一一對應(yīng)的,也就是說現(xiàn)實(shí)世界中每一個(gè)實(shí)體都是一個(gè)對象,它是一種具體的概念。本文主要介紹C++ 類的靜態(tài)成員變量和函數(shù)。
1、靜態(tài)成員變量
使用static關(guān)鍵字來把類成員變量定義為靜態(tài)的。當(dāng)我們聲明類的成員為靜態(tài)時(shí),即使多個(gè)類的對象,靜態(tài)成員都只有一個(gè)副本。
靜態(tài)成員變量在類的所有對象中是共享的。如果不存在其他的初始化語句,在創(chuàng)建第一個(gè)對象時(shí),所有的靜態(tài)數(shù)據(jù)都會被初始化為零。我們不能把靜態(tài)成員的初始化放置在類的定義中,但是可以在類的外部通過使用范圍解析運(yùn)算符 :: 來重新聲明靜態(tài)變量從而對它進(jìn)行初始化。
例如,
#include <iostream>
using namespace std;
class Area
{
   public:
      static int objectCount;
      // 構(gòu)造函數(shù)定義
      Area(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // 每次創(chuàng)建對象時(shí)增加 1
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // 長度
      double breadth;    // 寬度
      double height;     // 高度
};
// 初始化類 Area 的靜態(tài)成員
int Area::objectCount = 0;
int main(void)
{
   Area Area1(3.3, 1.2, 1.5);    // 聲明 Area1
   Area Area2(8.5, 6.0, 2.0);    // 聲明 Area2
   // 輸出對象的總數(shù)
   cout << "Total objects: " << Area::objectCount << endl;
   return 0;
}2、靜態(tài)成員函數(shù)
當(dāng)類成員函數(shù)聲明為靜態(tài)的,函數(shù)與類的任何特定對象相對獨(dú)立。靜態(tài)成員函數(shù)即使在類對象不存在的情況下也能被調(diào)用,靜態(tài)函數(shù)只要使用類名加范圍解析運(yùn)算符 :: 就可以訪問。
靜態(tài)成員函數(shù)只能訪問靜態(tài)成員數(shù)據(jù)、其他靜態(tài)成員函數(shù)和類外部的其他函數(shù)。
例如,
#include <iostream>
#include <string>
using namespace std;
class test
{
private:
    static int m_value;//定義私有類的靜態(tài)成員變量
public:
    test()
    {
    m_value++;
    }
    static int getValue()//定義類的靜態(tài)成員函數(shù)
    {
    return m_value;
    }
};
int test::m_value = 0;//類的靜態(tài)成員變量需要在類外分配內(nèi)存空間
int main()
{
    test t1;
    test t2;
    test t3;
    cout << "test::m_value2 = " << test::getValue() << endl;//通過類名直接調(diào)用公有靜態(tài)成員函數(shù),獲取對象個(gè)數(shù)
    cout << "t3.getValue() = " << t3.getValue() << endl;//通過對象名調(diào)用靜態(tài)成員函數(shù)獲取對象個(gè)數(shù)
}3、靜態(tài)成員函數(shù)與普通成員函數(shù)的區(qū)別
1)靜態(tài)成員函數(shù)沒有 this 指針,只能訪問靜態(tài)成員(包括靜態(tài)成員變量和靜態(tài)成員函數(shù))。
2)普通成員函數(shù)有 this 指針,可以訪問類中的任意成員;而靜態(tài)成員函數(shù)沒有 this 指針。
以上為本次所有分享內(nèi)容


 
             
             
            
 
             
             
            