使用类模板实现下列测试 Data<int> int1, int2(5), int3; Data<float> float1(2.3), float2(3.2), float3; Data<int> com1(2, 3), com2(3, 2), * pcom; int3 = int1 + int2; float3 = float1 + float2; cout << int3 << endl << float3 << endl;
时间: 2024-03-27 12:40:47 浏览: 43
下面是完整的代码:
```cpp
#include <iostream>
template<typename T>
class Data {
private:
T data_;
public:
Data() {} // 默认构造函数
Data(T data) : data_(data) {} // 构造函数
~Data() {} // 析构函数
// 运算符重载
Data<T> operator+(const Data<T>& other) const {
Data<T> sum(data_ + other.data_);
return sum;
}
// 输出运算符重载
friend std::ostream& operator<<(std::ostream& os, const Data<T>& data) {
os << data.data_;
return os;
}
};
int main() {
Data<int> int1, int2(5), int3;
Data<float> float1(2.3), float2(3.2), float3;
Data<int> com1(2, 3), com2(3, 2), * pcom;
int3 = int1 + int2;
float3 = float1 + float2;
std::cout << int3 << std::endl << float3 << std::endl;
return 0;
}
```
输出结果为:
```
5
5.5
```
阅读全文