C++ static變量的鉆牛角尖
來源:程序員人生 發布時間:2014-10-04 08:00:00 閱讀次數:7694次
最近面試的時候被問到了static的一些關于默認值,初始化,作用范圍一系列的問題,好多都不會,雖然面上了,回來還是想好好把這些東西復習一下。
static變量的默認值(即不進行賦值與調用默認構造函數)
類外聲明int float double 的static變量不初始化則默認值為0,可以使用不會報錯,指針類型的static變量默認值為NULL
類中聲明的static則默認沒有初始化,不初始化使用則不能通過編譯。
static變量的初始化
在類中聲明的static 變量不會也不能在類中初始化,但是在使用前必須在類的外部初始化,不初始化則編譯不通過
自定義的類的變量則會調用參數為空的構造函數進行對象的初始化,若沒有參數為空的構造函數則不能通過編譯
函數中的static變量會在函數執行的第一次進行初始化,之后便不進行初始化。類中的static變量在使用之前手動初始化。其他變量在main函數執行之前初始化。
static變量的訪問范圍
static聲明的函數如果在頭文件(.h)中同時包含的函數的定義,則在包含該頭文件外部文件可以使用,如果在(.h)文件中只是聲明了函數,函數定義卸載cpp文件中,則不能再包含該頭文件的外部文件中使用static函數
在。頭文件中聲明的static 變量可以在包含該頭文件的外部文件中使用
#include <iostream>
#include "ClassA.h"
using namespace std;
//類中的變量,沒有默認值,使用前必須初始化,
int ClassA::i = 10;
float ClassA::f = 110.1f;
double ClassA::d = 1.22;
ClassB ClassA::b;
//類外的變量,有默認值,已經初始化
static int i;
static float f;
static double d;
static ClassA* pa;
//沒有為空的構造函數,不能自動初始化
//static ClassA a1;
static ClassA a2("second");
void testInit()
{
ClassA a3("init");
}
int _tmain(int argc, _TCHAR* argv[])
{
//不初始化使用則編譯不通過
cout << ClassA::i << endl;
cout << ClassA::f << endl;
cout << ClassA::d << endl;
cout << i << endl; //0
cout << f << endl; //0
cout << d << endl; //0
if (pa == NULL)
{
cout << "NULL" << endl; //NULL
}
i = 10;
f = 10.1f;
d = 100.2;
cout << i << endl; //0
cout << f << endl; //10.1
cout << d << endl; //100.2
testInit(); //Class B init
testInit(); //已經初始化過了,不再初始化
system("pause");
return 0;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈