您的位置:首页 > 其它

类模板练习题——Template Arithmetic

2016-06-09 20:05 232 查看
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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 模板 练习题