// ************************************************************************** // // Counter.cpp // // Defines and tests class CounterType, which is used to count things. // CounterType contains both a default constructor and a constructor that // sets the count to a specified value, plus methods to increment, decrement, // return, and output the count. The count is always nonnegative. // // ************************************************************************** #include #include #include using namespace std; class CounterType { public: CounterType(); //Initializes the count to 0. CounterType(int initCount); //Precondition: initCount holds the initial value for the count. //Postcondition: // If initCount > 0,initializes the count to initCount. // If initCount <= 0,initializes the count to 0. void increment(); //Postcondition: // The count is one more than it was. void decrement(); //Postcondition: // If the count was positive, it is now one less than it was. // If the count was 0, it is still 0 int getCount(); void output(ostream& outStream); //Precondition: outStream is ready to write to //Postcondition: count has been written to outStream private: int count; }; void main () { int const limit = 50; CounterType ctype(100); cout << "Using mutator function to increase value:\n"; for (int i = 0; i < limit; i++) { ctype.output(cout); ctype.increment(); cout << " "; } cout << "\n\nUsing mutator function to decrease count:\n"; for (int i = 0; i < limit; i++) { ctype.output(cout); ctype.decrement(); cout << " "; } cout << "\n\nUsing the accessor function to access the private\n" << "count reveals that count is now: "; cout << ctype.getCount(); cout << endl; } CounterType::CounterType() { count = 0; } CounterType::CounterType(int initCount) { if (initCount >= 0) count = initCount; else count = 0; } void CounterType::increment() { count++; } void CounterType::decrement() { if (count > 0) count--; } int CounterType::getCount() { return count; } void CounterType::output(ostream& outStream) { outStream << count; } /* Output: Using mutator function to increase value: 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 Using mutator function to decrease count: 150 149 148 147 146 145 144 143 142 141 140 139 138 137 136 135 134 133 132 131 130 129 128 127 126 125 124 123 122 121 120 119 118 117 116 115 114 113 112 111 110 109 108 107 106 105 104 103 102 101 Using the accessor function to access the private count reveals that count is now: 100 Press any key to continue . . . */