C++ 中 static 關鍵字及其各種用法
當使用 static 關鍵字時,變數或資料成員或函式將無法再次修改。它被分配到程式的生命週期內。靜態函式可以直接使用類名呼叫。
靜態變數只初始化一次。編譯器將變數保留到程式結束。靜態變數可以在函式內部或外部定義。它們對塊是區域性的。靜態變數的預設值為零。靜態變數在程式執行期間一直存在。
以下是 static 關鍵字的語法。
static datatype variable_name = value; // Static variable
static return_type function_name { // Static functions
...
}這裡,
資料型別 − 變數的資料型別,例如 int、char、float 等。
變數名 − 這是使用者給定的變數名。
值 − 用於初始化變數的任何值。預設值為零。
返回型別 − 函式的資料型別,用於返回值。
函式名 − 函式的任何名稱。
以下是一個 static 關鍵字的示例。
示例
#include <bits/stdc++.h>
using namespace std;
class Base {
public : static int val;
static int func(int a) {
cout << "\nStatic member function is 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 is 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;
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP