Task:
1. Create a calculator class which will work for int values. Calculator class will include addition, subtraction, multiplication, and division function. Create object for the class. take user input for the numbers to add, subtract, divide, and multiply.
2. Write another class for Calculator which will work for all datatypes
Code:
C++ header: Calculator.h
#ifndef CALCULATOR_H_INCLUDED
#define CALCULATOR_H_INCLUDED
template<class T>
class Calculator
{
private:
T num1, num2;
public:
Calculator(T n1, T n2);
void displayResult();
T add();
T subtract();
T multiply();
T divide();
};
#endif // CALCULATOR_H_INCLUDED
C++ source: Calculator.cpp
#include<iostream>
#include "Calculator.h"
using namespace std;
template<class T>
Calculator<T>::Calculator(T n1, T n2)
{
num1 = n1;
num2 = n2;
}
template<class T>
void Calculator<T>::displayResult()
{
cout << "Numbers are: " << num1 << " and " << num2 << endl;
cout << "Addition is: " << add() << endl;
cout << "Subtraction is: " << subtract() << endl;
cout << "Product is: " << multiply() << endl;
cout << "Division is: " << divide() << endl;
}
template<class T>
T Calculator<T>::add()
{
return num1 + num2;
}
template<class T>
T Calculator<T>::subtract()
{
return num1 - num2;
}
template<class T>
T Calculator<T>::multiply()
{
return num1 * num2;
}
template<class T>
T Calculator<T>::divide()
{
return num1 / num2;
}
C++ main: main.cpp
#include <iostream>
#include "Calculator.h"
#include "Calculator.cpp"
using namespace std;
int main()
{
int n1, n2;
Calculator<int> intCalc(5, 5);
Calculator<float> floatCalc(2.4, 1.2);
cout << "Int results:" << endl;
intCalc.displayResult();
cout << endl << "Float results:" << endl;
floatCalc.displayResult();
return 0;
}
Output:
Int results:
Numbers are: 5 and 5
Addition is: 10
Subtraction is: 0
Product is: 25
Division is: 1
Float results:
Numbers are: 2.4 and 1.2
Addition is: 3.6
Subtraction is: 1.2
Product is: 2.88
Division is: 2
0 Comments