类模板练习题——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:
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()); }
相关文章推荐
- 设计模式之行为型模式 - 调用行为的传递问题
- [div+css]晒晒最新制作专题推广页模板
- Mootools 1.2教程 函数
- autoit InputBox 函数
- 2008大学生入党申请书 模板
- 文件遍历排序函数
- 关于C#中排序函数的总结
- Oracle 函数大全[字符串函数,数学函数,日期函数]第1/4页
- ASP下经常用的字符串等函数参考资料
- PostgreSQL教程(五):函数和操作符详解(1)
- DOS批处理 函数定义与用法
- asp Chr 函数 数字转字母的方法
- Lua中的函数精讲笔记
- Lua中的闭合函数、非全局函数与函数的尾调用详解
- Lua中调用C++函数示例
- Lua实现split函数
- Lua常用时间函数使用实例
- Lua函数与字符串处理简明总结
- Lua学习笔记之表和函数
- Lua中实现sleep函数功能的4种方法