类模板练习题——Template Arithmetic

本文介绍了一个通用模板类Arithmetic的实现,该类用于执行两个数值(int、double或float类型)之间的基本数学运算,包括加法、减法、乘法和除法,并通过示例演示了如何使用这个类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值