有沒(méi)有考慮過(guò),Static是如何實(shí)現(xiàn)的?
內(nèi)存和其他有何區(qū)別?
作為一位程序員,應(yīng)對(duì)自己的源代碼持有最謹(jǐn)慎的態(tài)度
#include <iostream>
using namespace std;
class A {
public:
static int num; // 統(tǒng)計(jì)創(chuàng)建了多少個(gè)實(shí)例
A () {
num++;
} // 每創(chuàng)建一個(gè)實(shí)例,就讓num自增1
// 返回通過(guò)構(gòu)造函數(shù)所創(chuàng)建過(guò)的A類實(shí)例的數(shù)目
static int how_many_instance() {
return num;
}
};
int A::num = 0; // 需要在類申明的外部單獨(dú)初始化!
int main() {
cout << A::how_many_instance() << endl;
A a, b, c, d;
cout << A::how_many_instance() << endl;
system("pause");
return 0;
}