-Define a class called Counter. An object of this class is used to count things.
ID: 3690456 • Letter: #
Question
-Define a class called Counter. An object of this class is used to count things. The class can be used to either count nonnegative whole numbers or nonnegative floating point numbers. The class should include two instance variables; one long and one double. -The class should include a three Constructors; a default Constructor with no parameters which initializes both variables to 0, and one Constructor each for initializing each instance variable. -The class should include two overloaded methods; add (2) and subtract (2). Each overloaded method is responsible for the count of each variable. Be sure that no method allows the value of the counter to become negative. - The class should include a toString() method, which can be used to display the two instance variables. - The class should include a static method reset(), which will set each of the two variables to 0. - Write a program to test your class definition. - Each method in the class should contain documentation as to its function.
Explanation / Answer
#include<iostream.h>
#include<stdlib.h>
class Counter
{
public:
long l;
double d;
Counter()
{
l=0;
d=0;
}
Counter(long lo)
{
l=lo;
}
Counter (double db)
{
d=db;
}
void add(long lo)
{
l=l+lo;
}
void add(double db)
{
d=d+db;
}
void subtract(long lo)
{
l=l-lo;
}
void subtract(double db)
{
d=d-db;
}
void toString()
{
cout<<"Long = "<<l;
cout<<"Double = "<<d;
}
void reset()
{
l=0;
d=0;
}
};
void main()
{
long l=123;
double d=11.33;
Counter o;
Counter o1(l);
Counter o2(d);
l=111;
d=112.33;
o.add(l);
o.add(d);
o.toString();
l=115;
d=124.7;
o1.add(l);
o1.add(d);
o1.toString();
l=156;
d=155.9;
o2.add(l);
o2.add(d);
o2.toString();
system("pause");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.