本题目要求定义类模板实现2个数的最大值、最小值、加、减、乘、除等算术运算,在main()函数中使用该类模板分别实例化为int型和double型的类,定义相关的对象,读入2个整数和2个浮点数,然后分别输出它们的最大值、最小值、加、减、乘、除的结果。
时间: 2023-10-17 14:05:37 浏览: 106
以下是实现要求的类模板示例代码:
```cpp
#include <iostream>
using namespace std;
template<typename T>
class Arithmetic{
private:
T num1, num2;
public:
Arithmetic(T n1, T n2){
num1 = n1;
num2 = n2;
}
T getMax(){
return (num1 > num2) ? num1 : num2;
}
T getMin(){
return (num1 < num2) ? num1 : num2;
}
T add(){
return num1 + num2;
}
T subtract(){
return num1 - num2;
}
T multiply(){
return num1 * num2;
}
T divide(){
return num1 / num2;
}
};
int main(){
int i1, i2;
double d1, d2;
cout << "Enter two integers: ";
cin >> i1 >> i2;
Arithmetic<int> ai(i1, i2);
cout << "Max = " << ai.getMax() << endl;
cout << "Min = " << ai.getMin() << endl;
cout << "Add = " << ai.add() << endl;
cout << "Subtract = " << ai.subtract() << endl;
cout << "Multiply = " << ai.multiply() << endl;
cout << "Divide = " << ai.divide() << endl;
cout << "Enter two doubles: ";
cin >> d1 >> d2;
Arithmetic<double> ad(d1, d2);
cout << "Max = " << ad.getMax() << endl;
cout << "Min = " << ad.getMin() << endl;
cout << "Add = " << ad.add() << endl;
cout << "Subtract = " << ad.subtract() << endl;
cout << "Multiply = " << ad.multiply() << endl;
cout << "Divide = " << ad.divide() << endl;
return 0;
}
```
示例输出:
```
Enter two integers: 10 5
Max = 10
Min = 5
Add = 15
Subtract = 5
Multiply = 50
Divide = 2
Enter two doubles: 3.14 2.71
Max = 3.14
Min = 2.71
Add = 5.85
Subtract = 0.43
Multiply = 8.5094
Divide = 1.15941
```
阅读全文