3 回答

TA貢獻1831條經驗 獲得超9個贊
static不幸的是,關鍵字在C ++中具有一些不同的不相關含義
當用于數據成員時,這意味著數據是在類中而不是在實例中分配的。
當用于函數內部的數據時,這意味著數據是靜態分配的,在第一次進入該塊時初始化,并持續到程序退出。此外,該變量僅在函數內部可見。局部靜態的這一特殊功能通常用于實現單例的惰性構造。
當在編譯單元級別(模塊)使用時,這意味著該變量就像一個全局變量(即在main運行之前分配和初始化,并在main退出后銷毀),但是在其他編譯單元中該變量將不可訪問或不可見。
我在每次使用中最重要的部分上加了一些強調。不鼓勵使用(3)來支持未命名的名稱空間,該名稱空間還允許未導出的類聲明。
在您的代碼中,static關鍵字的含義為2,與類或實例無關。它是函數的變量,將只有一個副本。
正如iammilind所說,如果該函數是模板函數,則可能存在該變量的多個實例(因為在這種情況下,函數本身確實可以在程序中的許多不同副本中出現)。即使在這種情況下,課程和實例都不相關...請參見以下示例:
#include <stdio.h>
template<int num>
void bar()
{
static int baz;
printf("bar<%i>::baz = %i\n", num, baz++);
}
int main()
{
bar<1>(); // Output will be 0
bar<2>(); // Output will be 0
bar<3>(); // Output will be 0
bar<1>(); // Output will be 1
bar<2>(); // Output will be 1
bar<3>(); // Output will be 1
bar<1>(); // Output will be 2
bar<2>(); // Output will be 2
bar<3>(); // Output will be 2
return 0;
}

TA貢獻2003條經驗 獲得超2個贊
函數內部的靜態變量
在函數內部創建的靜態變量存儲在程序的靜態存儲器中而不是堆棧中。
靜態變量初始化將在函數的第一次調用時完成。
靜態變量將在多個函數調用中保留該值
靜態變量的生命周期為Program
例子
#include <iostream>
using namespace std;
class CVariableTesting
{
public:
void FuncWithStaticVariable();
void FuncWithAutoVariable();
};
void CVariableTesting::FuncWithStaticVariable()
{
static int staticVar;
cout<<"Variable Value : "<<staticVar<<endl;
staticVar++;
}
void CVariableTesting::FuncWithAutoVariable()
{
int autoVar = 0;
cout<<"Variable Value : "<<autoVar<<endl;
autoVar++;
}
int main()
{
CVariableTesting objCVariableTesting;
cout<<"Static Variable";
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
objCVariableTesting.FuncWithStaticVariable();
cout<<endl;
cout<<"Auto Variable";
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
objCVariableTesting.FuncWithAutoVariable();
return 0;
}
輸出:
靜態變量
變量值:0
變量值1
變量值2
變量值3
變量值4
自動變數
變量值:0
變量值:0
變量值:0
變量值:0
變量值:0
- 3 回答
- 0 關注
- 416 瀏覽
添加回答
舉報