编程题(函数模板)。编写一个函数模板swapf,基本原型为: void swap( T &x, T &y);功能为交换2个参数x和y的值。然后编写主程序,分别交换整数、浮点数和字符串数据。
时间: 2024-12-19 16:25:14 浏览: 59
函数模板是一种通用的设计模式,在C++中允许程序员编写一次函数定义,然后可以在多种数据类型上应用。`swapf`函数模板的基本思想就是利用C++的模板特性,将类型的不确定性传递给编译器处理。以下是`swapf`函数模板的实现以及如何在主程序中使用它来交换不同类型的值(如整数(int)、浮点数(float)和字符串(string)`):
```cpp
// 定义swapf函数模板,接受任意类型T并引用两个变量x和y
template <typename T>
void swap(T& x, T& y) {
// 使用T的赋值运算符实现值的交换
T temp = x;
x = y;
y = temp;
}
int main() {
// 主程序部分,分别对不同类型的数据进行交换
int a = 5, b = 10;
swap(a, b);
std::cout << "After swapping integers: a = " << a << ", b = " << b << "\n";
float f1 = 3.14, f2 = 2.71;
swap(f1, f2);
std::cout << "After swapping floats: f1 = " << f1 << ", f2 = " << f2 << "\n";
std::string str1 = "Hello", str2 = "World";
swap(str1, str2);
std::cout << "After swapping strings: str1 = " << str1 << ", str2 = " << str2 << "\n";
return 0;
}
```
在这个例子中,当我们调用`swap(a, b)`、`swap(f1, f2)`和`swap(str1, str2)`时,编译器会根据相应的类型生成特定版本的`swap`函数,并完成实际的值交换。
阅读全文
相关推荐



















