Create a counter class, overload ++ operator for counter post and pre increment, use the
object of counter class as a loop counter for printing a table in main function.
#include <iostream>
#include <iomanip>
using namespace std;
class Counter {
int value;
public:
Counter(int v=0) : value(v) {}
Counter& operator++(); // Prefix
Counter operator++(int); // Postfix
int getValue() const {
return value;
}
};
Counter& Counter::operator++() {
value++;
return *this;
}
Counter Counter::operator++(int) {
Counter tmp = *this;
value++;
return *this;
}
int main() {
cout << " x | x^2" << endl;
for (Counter c(1); c.getValue()<=10; ++c) {
int x = c.getValue();
cout << setw(2) << x << " | " << setw(3) << x*x << endl;
}
return 0;
}
Comments
Leave a comment