C++ 中的 static 關鍵字


當使用 static 關鍵字時,變數、資料成員或函式將無法再次修改。它被分配到程式的整個生命週期。靜態函式可以直接使用類名呼叫。

靜態變數只初始化一次。編譯器會將變數保持到程式結束。靜態變數可以在函式內部或外部定義。它們對於該塊是區域性的。靜態變數的預設值為零。靜態變數在程式執行期間一直存在。

以下是 C++ 語言中 static 關鍵字的語法:

static datatype variable_name = value;      // Static variable
static return_type function_name {             // Static functions
   ...
}

這裡:

資料型別 - 變數的資料型別,例如 int、char、float 等。

變數名 - 這是使用者提供的變數名。

- 用於初始化變數的任何值。預設為零。

返回型別 - 函式返回的值的資料型別。

函式名 - 函式的任何名稱。

以下是一個 C++ 語言中靜態變數的示例:

示例

即時演示

#include <bits/stdc++.h>
using namespace std;
class Base {
   public : static int val;
   static int func(int a) {
      cout << "\nStatic member function called";
      cout << "\nThe value of a : " << a;
   }
};
int Base::val=28;
int main() {
   Base b;
   Base::func(8);
   cout << "\nThe static variable value : " << b.val;
   return 0;
}

輸出

Static member function called
The value of a : 8
The static variable value : 28

在上面的程式中,一個靜態變數被宣告,一個靜態函式在類 Base 中定義,如下所示:

public : static int val;
static int func(int a) {
   cout << "\nStatic member function called";
   cout << "\nThe value of a : " << a;
}

在類和 main() 之前,靜態變數初始化如下:

int Base::val=28;

在函式 main() 中,建立 Base 類的物件並呼叫靜態變數。靜態函式也無需使用 Base 類的物件即可呼叫,如下所示:

Base b;
Base::func(8);
cout << "\nThe static variable value : " << b.val;

更新於: 2019-07-30

14K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.