Hey guys, wrote this program with class templates to get the area of a rectangle. I placed it in a loop so the user could reset or end the program, but my teacher also wants double, long, and float datatypes so I was wondering if there was anyway to be able to use either of those datatypes without having to make another chunk of code in a separate loop?
rectangleArea<int> C1; //Access specifier
In the < > part, i Don't want to have to write another loop/if statement chunk of code just to make another class declaration key with a different < > datatype. Hopefully my question is clear, not really sure how to word it or the terminology to use..
#include <iostream>
#include <iomanip>
usingnamespace std;
//Program created by JOSH GIALIS to get area of two different Rectangles
//STEP 1: Define a class
template <class T>
class rectangleArea
{
private:
T length;
T width;
T answer;
public:
//Default Construtor to initialize variables, clear out RAM
rectangleArea() { T length = 0; T width = 0; T answer = 0; }
void setLength(T x)
{
length = x;
}
void setWidth(T y)
{
width = y;
}
T getArea()
{
answer = length * width;
return answer;
}
};
int main()
{
//STEP 2; DECLARE an instance of the class
int looper = 1; //Needed to run program again
for (int z = 0; z<looper; z++) {
int x, y;
rectangleArea<int> C1; //Access specifier
cout << "Please input length: " <<endl <<endl;
cin >> x;
// STEP 3: Use it with DOT notation
C1.setLength(x);
cout << "Please input width: " <<endl <<endl;
cin >> y;
C1.setWidth(y);
cout << "The area of the rectangle is " << C1.getArea() << " units sqaured. \n\n" ;
cout << "Use program again? Enter: [1] Yes or [2] No \n\n";
cin >> looper;
if (looper == 1) //If statement for program loop
{
looper++;
}
else
{
cout << "Thank you for using the program, goodbye. \n\n";
}
}
}