2016/04/25

static 與 const 關鍵字的用法與差異


static 與 const 原文都有 "固定的" 或 "不變的" 意思,如果放在 C++ 的 class 當中又是怎麼使用呢? 讓我們用以下範例解釋:

#include <iostream>
using namespace std;

class Demo {
 public:
  Demo() {
   cout << "*** construct new object  ***" << endl;
   static_count++;
   count++;
  }

  static int get_static_count() {
   cout << "static member \"static_count\" : " << static_count << endl;
   return 0;
  }

  int get_count() {
   cout << "non-static member \"count\" : " << count << endl;
   return 0;
  }

 private:
  const int const_count = 0;
  static int static_count;
  int count = 0;
};

int Demo::static_count = 0;

int main(void) {

 Demo d1;
 Demo::get_static_count(); 
 d1.get_count();
 cout << "----------------" << endl;

 Demo d2;
 d2.get_static_count(); 
 d2.get_count();
 cout << "----------------" << endl;

 Demo d3;
 d3.get_static_count(); 
 d3.get_count();
 cout << "----------------" << endl;

 return 0;
}

執行的結果如下所示:

*** construct new object ***
static member "sta_count" : 1
non-static member "count" : 1
----------------
*** construct new object ***
static member "sta_count" : 2
non-static member "count" : 1
----------------
*** construct new object ***
static member "sta_count" : 3
non-static member "count" : 1
----------------

在這個範例中 class "Demo" 有2個成員,初始值都設為0
static int sta_count;
int count = 0;
static 類型的成員只能在 class 之外設值
int Demo::static_count = 0;
我們用 class "Demo" 建立了 3 個物件,
每次新物件建立時,sta_count 以及 count 都做 +1 的動作

執行的結果顯示,"非" static 的變數每次都會隨著新物件 reset 為初始值
而 static 類型的變數,在整個程式中就是單獨唯一的,不會隨著新物件建立而產生新的副本
所以 static int sta_count 會累積數值,int count 不會

而設定為 const 類型的變數,則不能作任何更動
如 const_count ++ 編譯時會顯示錯誤

沒有留言:

張貼留言

Web 技術中的 Session 是什麼?

轉載原文:  Web 技術中的 Session 是什麼? 本文目標 在 Web 的世界裡,Session 已經是被廣泛使用的一種技術,大多數的 Web 開發者,肯定都能運用自如。在現今的各類 Web 應用程式的開發框架和工具中,Session 也已經被包裝成容易使用的模...