# re: static變量和static函數 回復 更多評論
2006-12-11 14:57 by
有沒有考慮過,Static是如何實現的?
內存和其他有何區別?
#include <iostream>
using namespace std;
class A {
public:
static int num; // 統計創建了多少個實例
A () {
num++;
} // 每創建一個實例,就讓num自增1
// 返回通過構造函數所創建過的A類實例的數目
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;
}