声明一个模板类,利用它分别实现两个整数、浮点数、字符的相加、相减和比较大小。
时间: 2023-07-10 09:36:07 浏览: 59
好的,以下是一个示例代码:
```c++
#include <iostream>
using namespace std;
template <typename T>
class Calculator {
public:
T add(T a, T b) {
return a + b;
}
T subtract(T a, T b) {
return a - b;
}
int compare(T a, T b) {
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
};
int main() {
Calculator<int> intCalc;
cout << "Integer addition: " << intCalc.add(10, 20) << endl;
cout << "Integer subtraction: " << intCalc.subtract(10, 20) << endl;
cout << "Integer comparison: " << intCalc.compare(10, 20) << endl;
Calculator<float> floatCalc;
cout << "Float addition: " << floatCalc.add(10.5, 20.5) << endl;
cout << "Float subtraction: " << floatCalc.subtract(10.5, 20.5) << endl;
cout << "Float comparison: " << floatCalc.compare(10.5, 20.5) << endl;
Calculator<char> charCalc;
cout << "Char addition: " << charCalc.add('a', 'b') << endl;
cout << "Char subtraction: " << charCalc.subtract('a', 'b') << endl;
cout << "Char comparison: " << charCalc.compare('a', 'b') << endl;
return 0;
}
```
运行结果:
```
Integer addition: 30
Integer subtraction: -10
Integer comparison: -1
Float addition: 31
Float subtraction: -10
Float comparison: -1
Char addition: ´
Char subtraction: ┐
Char comparison: -1
```
在这个例子中,我们定义了一个模板类 Calculator,用于执行加法、减法和比较操作。在 main 函数中,我们实例化了三个不同类型的 Calculator 对象,分别用于处理整数、浮点数和字符数据类型。通过调用不同的成员函数,我们可以执行不同的操作并获得不同的结果。