Monday, January 30, 2012

Static Members in Class

經static修飾的變數定義在Class中時,由於他的生命期是整份程式,並非單一個物件中,所以可以用來對於不同的class instance(物件)做運算,例如計算有多少個class instance:


myClass.h
class MyClass{
 public:
  //constructor
  MyClass();
  //destructor
  ~MyClass();
  //get the amount value
  static int getAmount();
 private:
  static int amount;
};

myClass.cpp
#include <iostream>
#include "myClass.h"

using namespace std;

int MyClass::amount = 0;

MyClass::MyClass(){
 amount++;
 cout << "no." << amount << " object built." << endl;
}

MyClass::~MyClass(){
 cout << "no." << amount << " object deleted." << endl;
 amount--;
}

int MyClass::getAmount(){
 return amount;
}

main.cpp
#include <iostream>
#include "myClass.h"

using namespace std;

void displayAmount();

int main(){

 if(1){
  MyClass a1;
  MyClass a2;
  displayAmount();

  MyClass b[2];
  displayAmount();
 }

 displayAmount();

 return 0;
}

void displayAmount(){
 cout << "Amount >> " << MyClass::getAmount() << endl;
}

Output
no.1 object built.
no.2 object built.
Amount >> 2
no.3 object built.
no.4 object built.
Amount >> 4
no.4 object deleted.
no.3 object deleted.
no.2 object deleted.
no.1 object deleted.
Amount >> 0

No comments:

Post a Comment