类模板练习题——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
- 类模板练习题——Template Arithmetic
- 函数模板练习题——template cmp
- 常用知识总结——模板Template
- 设计模式—模板模式(Template Pattern)
- C++ template - 类模板
- template 模板类
- c++ template 类模板
- C++类模板template
- 类模板-template
- C++模板类template
- template模板类使用
- 类模板Template
- C++类模板template
- c++ template 类模板特化
- 类模板template的使用!
- C++中的类模板Template
- C++template 模板类2
- C++模板类(Template)
- 利用栈将中缀表达式转换为后缀表达式
- C初级阶段练习题目(三)
- MacOS删除vpn
- ES6学习4(函数的拓展)
- arpspoof毒化
- 类模板练习题——Template Arithmetic
- 程序员提高效率的必备工具
- (三)JavaScript 的运算符,条件语句,循环语句..
- 电商之梳理mina相关知识---框架
- 电商之梳理jetty相关知识---服务器
- KMP算法-Java实现
- Node.js简单操作MongoDB(CRUD)
- Android之高德接口开发地图(-)
- Genymotion推送2.6.0后几个问题自己解决的办法