C++中的靜態物件何時被銷燬?
靜態物件用關鍵字 static 宣告。它們只初始化一次,儲存在靜態儲存區域。靜態物件只在程式終止時才會被銷燬,即它們一直存在,直到程式終止。
下面給出了一個演示 C++ 中靜態物件的程式。
示例
#include <iostream>
using namespace std;
class Base {
public :
int func() {
int a = 20;
cout << "The value of a : " << a;
}
};
int main() {
static Base b;
b.func();
return 0;
}輸出
上述程式的輸出如下。
The value of a : 20
現在讓我們瞭解一下上面的程式。
Base 類中的函式 func() 聲明瞭一個 int 變數 a,然後顯示 a 的值。展示此功能的程式碼片段如下。
class Base {
public :
int func() {
int a = 20;
cout << "The value of a : " << a;
}
};在主函式中,建立了類 Base 的靜態物件 b。然後呼叫函式 func()。由於物件 b 是靜態的,因此僅在程式終止時才會銷燬該物件。展示此功能的程式碼片段如下。
int main() {
static Base b;
b.func();
return 0;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP