allow an upper limit for the counter if no limit is specified when the object is
ID: 3828905 • Letter: A
Question
allow an upper limit for the counter
if no limit is specified when the object is created, the counter has no upper limit
allow the application programmer (i.e., the user of the class) to specify an initial value for the counter
if no initial value is specified, the initial value is 0.
the up function should respect the upper limit; i.e., calling up when the counter's value is at the upper limit has no effect on the value
when printing the counter, print the limit (in addition to the value), if one exists
add a reset function to the counter, setting it back to its initial value
add an equals operator that tests whether two Counters are equal (their values and limits are the same).
remove the >> operator
___________________________________________________________________________________________
Explanation / Answer
#include <iostream>
using namespace std;
class Counter {
public:
Counter(int initVal = 0,int upper=0) : val(initVal) {
reset_val=initVal;
upper_limit=upper;
}
void up() {
if(upper_limit!=val)
val++;
}
void down() {val--;}
int getVal() const {return val;}
void setLimit(int a)
{
upper_limit=a;
}
int getLimit()
{
return upper_limit;
}
int equal_to(Counter c)
{
if(val==c.getVal() && upper_limit==c.getLimit())
{
return 1;
}
return 0;
}
void reset()
{
val=reset_val;
}
private:
int val;
int upper_limit;
int reset_val;
};
int main() {
Counter c1;
c1.setLimit(25);
for (int i = 1; i < 20; i++)
c1.up();
cout << "c1.getVal() : " << c1.getVal() <<" c1.getLimit() : "<<c1.getLimit()<< endl;
for (int i = 1; i < 4; i++)
c1.down();
Counter c2(20,25);
cout << "c2.getVal() : " << c2.getVal() <<" c2.getLimit() : "<<c2.getLimit()<< endl;
Counter c3 = 45;
cout << "c3.getVal() : " << c3.getVal() <<" c3.getLimit() : "<<c3.getLimit()<< endl;
cout<<"Comparing Counter object c1 and c2 (if equal it will print 1 otherwise 0) : ";
cout<<c1.equal_to(c2)<<endl;
return 0;
}
//Output :
c1.getVal() : 19 c1.getLimit() : 25
c2.getVal() : 20 c2.getLimit() : 25
c3.getVal() : 45 c3.getLimit() : 0
Comparing Counter object c1 and c2 (if equal it will print 1 otherwise 0) :
0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.