Counter.h
#ifndef Counter_h #define Counter_h class Counter{ protected: int val; public: void reset2zero(); void upVal(); int getVal(); Counter(int initVal); Counter(); }; #endif
Counter.cpp
#include "Counter.h" void Counter::reset2zero(){ this->val = 0; } void Counter::upVal(){ this->val++; } int Counter::getVal(){ return this->val; } Counter::Counter(int initVal){ this->val = initVal; } Counter::Counter(){ reset2zero(); }
test.cpp
#include <iostream> using namespace std; #include "Counter.h" int main(){ const int n = 3; Counter cnt[n]; cnt[0] = Counter(10); cnt[1] = Counter(100); for(int i=0; i<2 ; i++){cnt[0].upVal();} for(int i=0; i<4 ; i++){cnt[1].upVal();} for(int i=0; i<10; i++){cnt[2].upVal();} for(int i=0; i<n; i++){ cout << cnt[i].getVal() << endl; } system("pause"); return 0; }