定义类模板实现2个数的算术运算 本题目要求定义类模板实现2个数的最大值、最小值、加、减、乘、除等算术运算,在main()函数中使用该类模板分别实例化为int型和double型的类,定义相关的对象,读入2个整数和2个浮点数,然后分别输出它们的最大值、最小值、加、减、乘、除的结果。以上是一个c++题目请帮我写一份实验报告
时间: 2023-07-10 14:10:39 浏览: 224
定义类模板实现2个数的算术运算
实验报告:定义类模板实现2个数的算术运算
实验目的
本实验旨在掌握C++中类模板的定义和使用方法,实现2个数的最大值、最小值、加、减、乘、除等算术运算,并在main()函数中使用该类模板分别实例化为int型和double型的类,定义相关的对象,读入2个整数和2个浮点数,分别输出它们的最大值、最小值、加、减、乘、除的结果。
实验原理
类模板
类模板是指一个通用的类描述,它可以定义一类类似的类,而不必为每一种类都单独定义一个类。类模板是用来产生类的蓝图,即类的模型。在定义类模板时,需要使用template关键字。类模板的参数可以是类型参数或非类型参数。
类模板的实例化
类模板的实例化是指将类模板产生的类具体化为某一特定类型的过程。当我们定义一个模板类对象时,需要指明所使用的类型。模板类对象的类型是通过模板参数来确定的。类模板实例化的方式有显示实例化和隐式实例化两种方式。
实验步骤
1.定义类模板Arithmetic
定义一个类模板Arithmetic,用于2个数的算术运算。在类模板中,定义泛型类型T,用于表示数据类型。在类中定义成员函数,实现最大值、最小值、加、减、乘、除等算术运算,代码如下:
```c++
template<typename T>
class Arithmetic {
public:
T getMax(T a, T b) {
return a > b ? a : b;
}
T getMin(T a, T b) {
return a < b ? a : b;
}
T add(T a, T b) {
return a + b;
}
T subtract(T a, T b) {
return a - b;
}
T multiply(T a, T b) {
return a * b;
}
T divide(T a, T b) {
return a / b;
}
};
```
2.在main()函数中使用类模板
在main()函数中,使用类模板Arithmetic分别实例化为int型和double型的类,定义相关的对象,读入2个整数和2个浮点数,分别输出它们的最大值、最小值、加、减、乘、除的结果,代码如下:
```c++
int main() {
Arithmetic<int> intArithmetic;
Arithmetic<double> doubleArithmetic;
int a, b;
double c, d;
cin >> a >> b >> c >> d;
cout << "Max of " << a << " and " << b << " is " << intArithmetic.getMax(a, b) << endl;
cout << "Min of " << a << " and " << b << " is " << intArithmetic.getMin(a, b) << endl;
cout << "Sum of " << a << " and " << b << " is " << intArithmetic.add(a, b) << endl;
cout << "Difference of " << a << " and " << b << " is " << intArithmetic.subtract(a, b) << endl;
cout << "Product of " << a << " and " << b << " is " << intArithmetic.multiply(a, b) << endl;
cout << "Quotient of " << a << " and " << b << " is " << intArithmetic.divide(a, b) << endl;
cout << "Max of " << c << " and " << d << " is " << doubleArithmetic.getMax(c, d) << endl;
cout << "Min of " << c << " and " << d << " is " << doubleArithmetic.getMin(c, d) << endl;
cout << "Sum of " << c << " and " << d << " is " << doubleArithmetic.add(c, d) << endl;
cout << "Difference of " << c << " and " << d << " is " << doubleArithmetic.subtract(c, d) << endl;
cout << "Product of " << c << " and " << d << " is " << doubleArithmetic.multiply(c, d) << endl;
cout << "Quotient of " << c << " and " << d << " is " << doubleArithmetic.divide(c, d) << endl;
return 0;
}
```
3.测试
输入两个整数和两个浮点数,例如:
```
2 3 1.5 2.5
```
程序运行结果如下:
```
Max of 2 and 3 is 3
Min of 2 and 3 is 2
Sum of 2 and 3 is 5
Difference of 2 and 3 is -1
Product of 2 and 3 is 6
Quotient of 2 and 3 is 0
Max of 1.5 and 2.5 is 2.5
Min of 1.5 and 2.5 is 1.5
Sum of 1.5 and 2.5 is 4
Difference of 1.5 and 2.5 is -1
Product of 1.5 and 2.5 is 3.75
Quotient of 1.5 and 2.5 is 0.6
```
实验结论
本实验通过定义类模板Arithmetic,实现2个数的最大值、最小值、加、减、乘、除等算术运算,并在main()函数中使用该类模板分别实例化为int型和double型的类,定义相关的对象,读入2个整数和2个浮点数,分别输出它们的最大值、最小值、加、减、乘、除的结果。实验结果表明,类模板可以实现不同数据类型的通用算术运算,提高了代码的复用性。
阅读全文