-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator_template.cpp
More file actions
50 lines (41 loc) · 1.13 KB
/
calculator_template.cpp
File metadata and controls
50 lines (41 loc) · 1.13 KB
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
/*
* File: calculator_template.cpp
* Problem:
* Create a class template Calculator that performs basic operations
* (addition, multiplication) for both integer and double values.
*/
#include <iostream>
using namespace std;
// create class template Calculator
template <typename T>
class Calculator {
public:
// variables of T type
T num1, num2;
// constructor initializer list
Calculator(T n1, T n2) : num1(n1), num2(n2) {}
// calculate function with operator parameter
T calculate(char op) {
if (op == '+')
return num1 + num2;
else if (op == '*')
return num1 * num2;
else
return static_cast<T>(0.0); // return 0 of type T
}
};
int main() {
// get input values
int n1, n2;
double n3, n4;
cin >> n1 >> n2 >> n3 >> n4;
// create Calculator object for integer type
Calculator<int> obj1(n1, n2);
int result1 = obj1.calculate('*');
// create Calculator object for double type
Calculator<double> obj2(n3, n4);
double result2 = obj2.calculate('+');
// print results
cout << result1 << endl << result2;
return 0;
}