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 >> 2no.3 object built.no.4 object built.Amount >> 4no.4 object deleted.no.3 object deleted.no.2 object deleted.no.1 object deleted.Amount >> 0
No comments:
Post a Comment