设计一个函数模板,交换同类型两个变量的值,能处理的数据包括能够int、char 、float、double、long、long long、char*,注意对C风格字符串(char*)数据的处理。
时间: 2024-03-18 09:41:39 浏览: 234
好的,这是一个交换同类型两个变量值的函数模板,支持int、char、float、double、long、long long和char*类型的数据:
```c++
#include <cstring>
template<typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
template<>
void swap<char*>(char*& a, char*& b) {
char* temp = new char[strlen(a) + 1];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
delete[] temp;
}
```
对于大部分类型,我们可以直接使用T类型的变量进行交换,但对于C风格字符串(char*)类型的变量,我们需要手动进行内存分配和字符串拷贝,避免指针被重复释放或者内存泄漏等问题。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)