Your First Class
Completed
Write a class Counter with a private int count, and public increment(), reset() and value(). Process commands inc, reset, show.
Input
n, then n commands.
Output
One line per show.
Example
Input
6 inc inc show reset inc show
Output
2 1
Editor
C++
Hints
Members are private by default in a class; put the interface under public:.
Solution explanation
Private data can only be changed through the class's own methods - that's encapsulation.
Show solution
#include <iostream>
#include <string>
using namespace std;
class Counter {
public:
void increment() { count++; }
void reset() { count = 0; }
int value() const { return count; }
private:
int count = 0;
};
int main() {
Counter c;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string cmd;
cin >> cmd;
if (cmd == "inc") c.increment();
else if (cmd == "reset") c.reset();
else cout << c.value() << "\n";
}
return 0;
}