C++ 中類成員函式中的靜態變數如何工作?
成員函式中的靜態變數使用關鍵字 static 宣告。靜態變數的空間只分配一次,並且在整個程式中使用它。此外,整個程式中只有這些靜態變數的一個副本。
一個演示 C++ 中成員函式中靜態變數的程式如下所示。
示例
#include <iostream>
using namespace std;
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};
int main() {
Base b;
b.func();
return 0;
}輸出
上述程式的輸出如下。
The default value of static variable a is: 0 The value of static variable b is: 12
現在讓我們理解一下上述程式。
類 Base 中的成員函式 func() 包含兩個靜態變數 a 和 b。a 的預設值為 0,b 的值為 12。然後將這些值顯示出來。顯示它的程式碼片段如下。
class Base {
public :
int func() {
static int a;
static int b = 12;
cout << "The default value of static variable a is: " << a;
cout << "\nThe value of static variable b is: " << b;
}
};在 main() 函式中,建立了類 Base 的物件 b。然後呼叫函式 func()。顯示它的程式碼片段如下。
int main() {
Base b;
b.func();
return 0;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP