定义一个类模板来实现三个数比较大小,分别用两个成员函数max()和min()返回最大值和最小值。要求不仅能够处理整型、实型、字符型等基本数据,而且能够正确处理字符串。
时间: 2024-03-22 10:38:14 浏览: 78
好的,以下是一个满足要求的类模板的示例代码:
```c++
#include <iostream>
#include <string>
template<typename T>
class Compare
{
public:
Compare(T a, T b, T c) : x(a), y(b), z(c) {}
T max()
{
T result = x;
if (y > result) result = y;
if (z > result) result = z;
return result;
}
T min()
{
T result = x;
if (y < result) result = y;
if (z < result) result = z;
return result;
}
private:
T x, y, z;
};
template<>
class Compare<std::string>
{
public:
Compare(std::string a, std::string b, std::string c) : x(a), y(b), z(c) {}
std::string max()
{
std::string result = x;
if (y > result) result = y;
if (z > result) result = z;
return result;
}
std::string min()
{
std::string result = x;
if (y < result) result = y;
if (z < result) result = z;
return result;
}
private:
std::string x, y, z;
};
int main()
{
Compare<int> c1(1, 2, 3);
std::cout << "Max: " << c1.max() << std::endl;
std::cout << "Min: " << c1.min() << std::endl;
Compare<double> c2(1.1, 2.2, 3.3);
std::cout << "Max: " << c2.max() << std::endl;
std::cout << "Min: " << c2.min() << std::endl;
Compare<char> c3('a', 'b', 'c');
std::cout << "Max: " << c3.max() << std::endl;
std::cout << "Min: " << c3.min() << std::endl;
Compare<std::string> c4("apple", "banana", "cherry");
std::cout << "Max: " << c4.max() << std::endl;
std::cout << "Min: " << c4.min() << std::endl;
return 0;
}
```
这个类模板中,我们用了一个通用的模板类型 `T`,并在类模板中定义了两个成员函数 `max()` 和 `min()`,用来返回三个数中的最大值和最小值。在类模板中,我们还特化了一个 `std::string` 类型的版本,以支持字符串类型的比较。在 `main()` 函数中,我们分别测试了该类模板对整型、实型、字符型和字符串类型的支持,并输出了结果。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)