类模板练习题——Template Arithmetic

来源:互联网 发布:福州专业淘宝美工培训 编辑:程序博客网 时间:2024/06/01 14:21

Description:

In this exercise, you are required to implement a template Arithmetic, which takes two parameters of type int,double,float, and then provides four kinds of operations including addition, subtraction, multiplication and division.

The declaration will not be given below and you should implement the declaration and its functions according to the main function given below.

You don’t have to consider the situation when the divisor is 0 in division.

Here is my answer:

//Arithmetic.h:template<typename T>class Arithmetic { private:    T a;    T b; public:    Arithmetic();    Arithmetic(T a, T b);    ~Arithmetic();    T addition();    T subtraction();    T multiplication();    T division();};
//Arithmetic.cpp:#include "Arithmetic.h"template<typename T>Arithmetic<T>::Arithmetic() {    a = b = 0;}template<typename T>Arithmetic<T>::Arithmetic(T a, T b) {    this->a = a;    this->b = b;}template<typename T>Arithmetic<T>::~Arithmetic() {}template<typename T>T Arithmetic<T>::addition() {    return a + b;}template<typename T>T Arithmetic<T>::subtraction() {    return a - b;}template<typename T>T Arithmetic<T>::multiplication() {    return a * b;}template<typename T>T Arithmetic<T>::division() {    return a / b;}
//test.cpp:#include <iostream>#include "Arithmetic.h"using std::cin;using std::cout;using std::endl;template< typename T >void printResult(T number) {    cout << "The result of the operation is: " << number << endl;}int main() {    Arithmetic< int > a(5, 3);    Arithmetic< double > b(7.3, 5.2);    cout << "Arithmetic performed on object a:\n";    printResult(a.addition());    printResult(a.subtraction());    printResult(a.multiplication());    printResult(a.division());    cout << "\nArithmetic performed on object b:\n";    printResult(b.addition());    printResult(b.subtraction());    printResult(b.multiplication());    printResult(b.division());}
0 0