Class Templates

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..

Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  
#include <iostream>
#include <iomanip>

using namespace 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";
        }
    }
}



You should place a break; after the cout on line 71.

Apart from that: Put the loop in a template function in order to use the different types.
Topic archived. No new replies allowed.