# re: static變量和static函數(shù) 回復 更多評論
2006-12-11 14:57 by
有沒有考慮過,Static是如何實現(xiàn)的?
內(nèi)存和其他有何區(qū)別?
# re: static變量和static函數(shù) 回復 更多評論
2010-04-10 10:55 by
作為一位程序員,應對自己的源代碼持有最謹慎的態(tài)度
#include <iostream>
using namespace std;
class A {
public:
static int num; // 統(tǒng)計創(chuàng)建了多少個實例
A () {
num++;
} // 每創(chuàng)建一個實例,就讓num自增1
// 返回通過構造函數(shù)所創(chuàng)建過的A類實例的數(shù)目
static int how_many_instance() {
return num;
}
};
int A::num = 0; // 需要在類申明的外部單獨初始化!
int main() {
cout << A::how_many_instance() << endl;
A a, b, c, d;
cout << A::how_many_instance() << endl;
system("pause");
return 0;
}